Simple Program Using Array
Let us try to write a program to find average marks obtained by a class of 100 students in a test.Using array,the multiple variable declaration can be reduced and it becomes easy to handle the programming problems.
[c] void main(){
int i, sum = 0;
float avg;
int mark[100]; /* array declaration */
for (i = 0; i <100 ; i++) { printf ("\nEnter marks"); scanf ("%d", &mark[i]); /* store data in array */ } for (i = 0 ; i <100; i++) sum = sum + mark[i]; /* read data from an array*/ avg = (float)sum / 30 ; /*type casting of int to float*/ printf ("\nAverage marks = %.2f", avg); getch(); } [/c]
Array Declaration
An array needs to be declared so that the compiler will know what kind of an array and how large an array we want. In our program we have done this with the statement:
[c]
int mark[100];
[/c]
Here, int specifies the type of the variable, just as it does with urinary variables and the word mark specifies the name of the variable. The [c][100][/c] however is new. The number 100 tells how many elements of the type int will be in our array. The bracket [c]( [ ] )[/c] tells the compiler that we are dealing with an array.
Accessing Elements,in simple program using array
Once an array is declared, individual elements in the array can be referred. This is done with subscript, the number in brackets following the array name. This number specifies the element’s position in the array. All the array elements are numbered, starting with 0. Thus, marks|2] is not the second clement of the array, but the third. In our program we are using the variable i as a subscript to refer to various elements of the array. This variable can take different values and hence can refer to the different elements in the array in turn. This ability to use variables as subscripts is what makes arrays so useful.
Entering Data into an Array
Here is the section of code that places data into an array:
[c] for (i = 0 ; i <100 ; i++) { print! ("\nEnter marks"); scant ("%d", &mark[i]); } [/c] The for loop causes the process of asking for and receiving a student's marks from the user to be repeated 100 times. The first time through the loop, i has a value 0, so the scanf( ) statement will cause the value typed to be stored in the array element marks[0], the first element of the array. This process will be repeated until i becomes 99. In the scanf( ) statement, we have used the "address of operator (&) on the element marks[i] of the array. In so doing, we are passing the address of this particular array element to the scanf( ) function, rather than its value.Array in C programming are very interesting concept.Array is used for storing the similar types of variable.In most of the cases, array is refferred but in high level of C programming pointer is also applicable with array.