In C programming, one of the frequently arising problem is to handle similar types of data. For example: If the user want to store marks of 100 students. This can be done by creating 100 variable individually but, this process is rather tedious and impracticable. These type of problem can be handled in C programming using arrays.
An array is a sequence of data item of homogeneous value(same type).
Arrays are of two types:
- One-dimensional arrays
- Multidimensional arrays( will be discussed in next chapter )
Declaration of one-dimensional array
Here, the name of array is age. The size of array is 5,i.e., there are 5 items(elements) of array age. All element in an array are of the same type (int, in this case).
Size of array defines the number of elements in an array. Each element of array can be accessed and used by user according to the need of program. For example:
Note that, the first element is numbered 0 and so on.
Here, the size of array age is 5 times the size of int because there are 5 elements.
Suppose, the starting address of
age is 2120d and the size of int be 4 bytes. Then, the next address (address of
a) will be 2124d, address of
a will be 2128d and so on.
Initialization of one-dimensional array:
Arrays can be initialized at declaration time in this source code as:
It is not necessary to define the size of arrays during initialization.
In this case, the compiler determines the size of array by calculating the number of elements of an array.
Accessing array elements
In C programming, arrays can be accessed and treated like variables in C.
/* statement to insert value in the third element of array age. */
/* Statement to insert value in (i+1)th element of array age. */
/* Because, the first element of array is age, second is age, ith is age[i-1] and (i+1)th is age[i]. */
/* statement to print first element of an array. */
/* statement to print (i+1)th element of an array. */
Example of array in C programming
/* C program to find the sum marks of n students using arrays */
printf("Enter number of students: ");
printf("Enter marks of student%d: ",i+1);
Enter number of students: 3
Enter marks of student1: 12
Enter marks of student2: 31
Enter marks of student3: 2
Important thing to remember in C arrays
Suppose, you declared the array of 10 students. For example:
arr. You can use array members from
arr. But, what if you want to use element
arr etc. Compiler may not show error using these elements but, may cause fatal error during program execution.