what is an array
Array is collection of elements having simmilar datatype.
How to declare an array
data_tpye arrayname[size];
for e.g. int a[10];
A Simple Program Using Array
Let us try to write a program to find average marks obtained by a class of 30 students in a test.
void main( ) { int avg, sum = 0 ; int i ; int marks[30] ; for ( i = 0 ; i <= 29 ; i++ ) { printf ( "\nEnter marks " ) ; scanf ( "%d", &marks[i] ) ; } for( i = 0 ; i <= 29 ; i++ ) sum = sum + marks[i] ; avg = sum / 30 ; printf ( "\nAverage marks = %d", avg ) ; }
Properties of an array
(a)An array is a collection of similar elements.
(b)The first element in the array is numbered 0, so the last element is 1 less than the size of the array.
(c)However big an array its elements are always stored in contiguous memory locations. This is a very important point which we would discuss in more detail later on.
Array Initialization
Following are some ways to initialize an array
1) int num[6] = { 2, 4, 12, 5, 45, 5 } ;
2) int n[ ] = { 2, 4, 12, 5, 45, 5 } ;
3) float press[ ] = { 12.3, 34.2 -23.4, -11.3 }
In the 2nd and 3rd case we have not defined the size of the array but depending upon the the elements present it takes the size for e.g. array size of int n[] is 6 and array size of float press[] is 4.
the values inside array are stored in following manner
int n[0] = 2;
int n[1] = 4;
int n[2] = 12;
int n[3] = 5;
int n[4] = 45;
int n[5] = 5;
2 D array
we have seen arrays with only one dimension. It is also possible for arrays to have two or more dimensions. The two-dimensional array is also called a matrix.
it is declared as int a[3][3];
elements are store in this array in following manner
0 | 1 | 2 | |
0 | [0][0] | [0][1] | [0][2] |
1 | [1][0] | [1][1] | [1][2] |
2 | [2][0] | [2][1] | [2][2] |
below is an example of 2D array. It takes the array input and displays it.
void main() { int i, j, a[3][3]; for(i = 0; i<3; i = i + 1) { for(j = 0; j <3; j = j + 1) { printf("\nEnter value a[%d][%d] = ",a[i][j]); scanf("%d%d", &a[i][j]); } } for(i = 0; i<3; i = i + 1) { for(j = 0; j <3; j = j + 1) printf("a[%d][%d] = %d\t", i, j, a[i][j]); printf("\n"); } }
output:
1 2 3
4 5 6
7 8 9