Sunday, 20 May 2012

how to access array elements

Array is collection of similar type of data stored in contiguous memory. Here i will show how array is mapped in memory.Let's suppose we have array of students roll
numbers .

int  student_roll[4];

Above line creates four spaces in memory.



 where first element is called base element of array and named following syntex

                                            arrayname[index]

here index denotes position of element. In memory array starts from 0 index. So
base element is   student_roll[0]
similarly

second element is  student_roll[1]
third element is      student_roll[2]
and fourth element is student_roll[3]

we can access all elements using concept of  looping
int i;

for(i=0;i<4;i++)
{
   code for printf() or scanf() using student_roll[i]
}

here i works as counter who count index of array.

Input in array

for putting data in memory we use scanf() function.

putting data at base(first) element    scanf("%d",&student_roll[0]);

putting data at second element           scanf("%d",&student_roll[1]);
putting data at third  element             scanf("%d",&student_roll[2]);

putting data at forth element              scanf("%d",&student_roll[3]);

Using looping

for(i=0;i<4;i++)
{
  scanf("%d",&student_roll[i]);
}



Output in array

for getting data from memory we use printf() function.

getting data from base(first) element    printf("%d",student_roll[0]);

getting data from second element           printf("%d",student_roll[1]);
getting data from third  element             printf("%d",student_roll[2]);

getting data from forth element              printf("%d",student_roll[3]);




Using looping


for(i=0;i<4;i++)
{
  printf("%d",student_roll[i]);
}



 thus we learn how to access elements of array for input and output purpose.


Read latest blog




















No comments:

Post a Comment