Friday 6 March 2015

Initialising an Array in C

An array will not be initialised when it is declared; therefore its contents are undetermined until we store some values in it. The following array can hold marks for five subjects.

int marks[5];
 
The elements of an array can be initialised in two ways. In the first approach, the value of each element of the array is listed within two curly brackets ({}) and a comma (,) is used to separate one value from another. 

For example:
 
marks[5] = {55, 33, 86, 81, 67};

In the second approach elements of the array can be initialised one at a time. This approach makes use of the format:

array-name[index];

For example:
 
marks[0] = 55;
marks[1] = 33;
marks[2] = 86;
marks[3] = 81;
marks[4] = 67;

In an array index of the first element is considered as zero rather than one. Therefore in an array with “n” elements first index is “0” and the last index is “n-1”. This confusion can be overcome by initialising an array with “n+1” elements and neglecting the first element (element with zero index). 

Consider the following example:
 
/* Program-6.1 */
 
#include <stdio.h>
 
int main()
{
int i,sum;
int marks[5]; //array of 5 elements
float average;
sum=0;
for(i=0;i<5;i++)
{
printf("Enter marks for subject %d: ", i+1);
scanf("%d", &marks[i]); //get the marks
}
for(i=0;i<=5;i++) //total marks
{
sum +=marks[i];
}
average = sum/5.0; //5.0 indicates a float value
printf("Average : %.2f", average);
return 0;
}
Execution of Program-6.1 displays the following:

Enter marks for subject 1: 55
Enter marks for subject 2: 33
Enter marks for subject 3: 86
Enter marks for subject 4: 81
Enter marks for subject 5: 67
 
Average : 64.60

The Program-6.1 accepts marks for 5 subjects from the keyboard and stores them in an array named marks. Then in the second loop it computes total of all marks stored in the array and finally it computes the average.


No comments:

Post a Comment