Monday, 18 September 2017

Array In C

ARRAY IN C

void main( )
{
int x ;
x = 5 ;
x = 10 ;
printf ( "\nx = %d", x ) ;
}
This program will print the value of x as 10. Why so? Because when a value 10 is assigned to x, the earlier value of x, i.e. 5, is lost. However, there are situations in which we would want to store more than one value at a time in a single variable.In that situation, Array comes into existence.

An array is a collective name given to a group of ‘similar data members’. This similar data member could be percentage marks of 100 students or ages of 50 employees or names of employees.

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] ; /* array declaration */
 for ( i = 0 ; i <= 29 ; i++ )
 {
 printf ( "\nEnter marks " ) ;
 scanf ( "%d", &marks[i] ) ; /* store data in array */
 }
 for ( i = 0 ; i <= 29 ; i++ )
 sum = sum + marks[i] ; /* read data from an array*/
 avg = sum / 30 ;
 printf ( "\nAverage marks = %d", avg ) ;


Array Declaration


Like other variables, an array needs to be declared so that the compiler will know what kind of an array and how large an array we want.

int marks[30] ; 

Here, int specifies the type of the variable, just as it does with ordinary variables and the word marks specifies the name of the variable. The [30] however is new. The number 30 tells how many elements of the type int will be in our array.

Entering Data into an Array 


for ( i = 0 ; i <= 29 ; i++ )
{
 printf ( "\nEnter marks " ) ;
 scanf ( "%d", &marks[i] ) ;


The first time through the loop, i has a value 0 so the scanf( ) function 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 29.

Reading Data from an Array


for ( i = 0 ; i <= 29 ; i++ )
 sum = sum + marks[i] ;
avg = sum / 30 ;
printf ( "\nAverage marks = %d", avg ) ; 

The for loop is much the same, but now the body of the loop causes each student’s marks to be added to a running total stored in a variable called sum. When all the marks have been added up, the result is divided by 30, the number of students, to get the average.


Array Initialisation

Let us now see how to initialize an array while declaring it. Following are a few examples that demonstrate this.
int num[6] = { 2, 4, 12, 5, 45, 5 } ;
int n[ ] = { 2, 4, 12, 5, 45, 5 } ;
float arr[ ] = { 12.3, 34.2 -23.4, -11.3 } ; 

Important points:-
(a) Till the array elements are not given any specific values, they are supposed to contain garbage values.
(b) If the array is initialized where it is declared, mentioning the dimension of the array is optional as in the 2nd example above. 

No comments:

Post a Comment