Accessing Elements in an Array

Accessing Elements in an Array

Published by: Nuru

Published date: 21 Jun 2021

Accessing Elements in an Array Photo

Accessing Elements in an Array

Accessing Elements in an Array simply refers to the specifying of an offset or index of the desired element within the square brackets after the array name. These subscripts as mentioned earlier are of the same data type.

Once the array is declared, a single operation that involves an entire array is not permitted in C. Generally, there is the use of a loop in accessing the elements of the array. Access here means input and output.

The nth element can be accessed as int [n].

We are using n as a subscript to refer to the various elements of the array. This can take different values and refer to the different elements in the array.

For example:

int a [5], b[5], x;

x = a [0] + 10;

a[4] = a[1] + a[2];

b[3] = b[0] + a[3] + x;

 

Reading the elements of an array

For instance, let us take an example,

int i;

int marks [4];

for ( i = 0; i< = 3; i++ )

{

printf ( “/n Input marks of the given subject “);

scanf (“ %d &marks [i];

}

Here, the 'for' loop will cause the process to ask for and receive a student’s marks 4 times. The first time in the loop, 'i' has 0 value. So, scanf () function will cause the value type storing in the array element marks[0]. This loop will work until and unless the value of i is 3.

 

Accessing Data

We know that for reading data in the array, there is a use of loop for loading data.

Let us suppose, we need to find out the total marks of 5 subjects.

then the program for it will look like,

int marks [5] , i, sum = 0;

for ( i=0, i< 5; i++)

sum = sum + marks [i];

printf ( “/n Total marks  = %d”, sum );

The above program accepts the marks of five subjects from the user and stores them in an array named marks. This is only known as the accessing of data. That is, the data input that the user provides is accessed using an array.