Array Initialization
The array initialization is done as given below-
int arr [5] = {5, 4, 3, 2, 1};
Here, 5 elements are stored in an array 'arr'. The array elements are stored sequentially in separate locations. Array elements are called by array names followed by the element number.
arr [0] refers to 1st element i.e. 5
arr [1] refers to 1st element i.e. 4
arr [2] refers to 1st element i.e. 3
arr [3] refers to 1st element i.e. 2
arr [4] refers to 1st element i.e. 1
arr [0] refers to 1st element i.e. 5
arr [1] refers to 1st element i.e. 4
arr [2] refers to 1st element i.e. 3
arr [3] refers to 1st element i.e. 2
arr [4] refers to 1st element i.e. 1
The other way of initializing is-
int arr [ ] = {1, 2, 3, 4, 5};
Important Points:
1. If array elements are not given a value, they are supposed garbage values.
2. If array is initialized at declaration time, then dimension of array is optional.
Array Elements In Memory:
Consider the following array declaration-
int arr[5];
When we make this declaration 10 bytes get reserved in memory. Because, each of 5 integers would be of 2 bytes long. As we know all the array elements are always stored in contiguous memory locations. This arrangement of array elements in memory is shown in figure:-
arr[0] arr[1] arr[2] arr[3] arr[4] Elements
Value
2001 2003 2005 2007 2009 Address
A Simple Program Using Array:
Program to accept 10 numbers and print them.
main()
{
int arr [10],i;
for(i=0; i<=10; i++)
{
printf("\nEnter the number");
scanf("%d",&arr[i]);
}
for(i=0; i<=10; i++)
{
printf("%d\n",arr[i]);
}
}