Arrays are generally used to store related data under a single variable name with an index. To create an array, we have to define the data type (like int) and specify the name of the array followed by square brackets[].
C Arrays
Type name[number of elements];
For e.g:-
int arr[10];
we can also initialize while we declare them. We can usually put the initial elements in curly brackets separated by commas :
type name[number of elements]={comma-separated values};
Though when the array is initialized as shown below, the array dimension may be omitted, and the array will be automatically sized to hold the initial data:
int arr[]={0,0,1,0,1,0};
This can be very useful as the size of the array can be modified just by adding or removing initializer elements from the definition even without the need to adjust the dimension.
If all elements of array are not initialized but dimension is specified, the remaining elements will contain a value of 0.This proves useful when we have very large arrays.
int numbers[2000]={0};
In above example the first value of the array is set to 245 and the rest are set to 0.
We can access a variable stored in an array also. Following is the code for that:-
int x;
x= arr[2];
Arrays in C are 0-indexed starting with 0 not like 1 based indexing starting with 1. The first element of the array above can be is accessed as arr[0]. The last index value in the array can be accessed as array size-1. C does not always perform bound checking while accessing array. There is a chance that compiler may not complain about the following code:-
char y;
int z=9;
char arr[6]={1,2,3,4,5,6};
y=arr[15];
y=arr[-4];
y=arr[z];
When the program is in execution,run time error is not always caused by an out of bounds array. The program may continue running after retrieving a value from point[-1]. The indexing problems can be reduced by using the sizeof() expression which is commonly used when coding loops that process arrays.
Looping through an array
We can loop through the array using or loop. Here is the program which shows a general code of a for loop:
int myNumbers[] = {25, 50, 75, 100};
int i;
for (i = 0; i < 4; i++) {
printf("%d\n", myNumbers[i]);
}