Reading Data from an Array

Reading data from an Array

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 100, the number of students, to get the average.

[c] for (i = 0; i <100; i++) { sum = sum + mark[i]; } avg = (float)sum / 100 ; printf ("\nAverage marks = %.2f", avg); [/c] Points to be remembered about array:
  • An array is a collection of similar elements
  • The first element in the array is numbered 0, so the last element is 1 less than the size of the array.
  • An array is also known as a subscripted variable
  • Before using an array its type and dimension must be declared
  • 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 a few examples which shows how the array is initialized
[c] int age[6] = {2, 4,12, 5,45,5};
int value[ ] = {2,4,12,5,45, 5};
float indexl[ ] = {14.30, 44.2,-78.4, 17.3};
[/c] Note the following points carefully:

  • Till the array elements are not given any specific values, they are supposed to contain garbage values.
  • If the array is initialized where it is declared, mentioning the dimension of the array is optional as in the 2nd example above.

Array Elements in Memory

Consider the following array declaration:
[c] int sal[8];[/c]

16 bytes get immediately reserved in memory, 2 bytes each for the 8 integers. And since the array is not being initialized, all eight values present in it would be garbage values. This so happens because the storage class of this array is assumed to be auto. If the storage class is declared to be static then all the array elements would have a default initial value as zero. Whatever be the initial values, all the array elements would always be present in contiguous memory locations.Reading data from an array is simple and important because all the processing is based on the data. This arrangement of array elements in memory is shown in Figure below.

reading data from an array
reading data from an array
This entry was posted in Uncategorized. Bookmark the permalink.