About Me

My photo
Raipur, Chhattisgarh, India
Hi , I am Amit Thakur. I have worked as a QA Engineer for two years and as a Java Developer for one year in NIHILENT TECHNOLOGIES PVT. LTD., Pune.Currently I am working as DEAN (Research & Development) in Bhilai Institute of Technology, Raipur.

Friday, August 30, 2013

Write a ‘C’ Program to compute the sum of all elements stored in an array using pointers

C Program to compute sum of the array elements using pointers

Program :

#include<stdio.h>
#include<conio.h>
void main()
{
 int a[10];
 int i,sum=0;
 int *ptr;

 printf("Enter 10 elements:n");

 for(i=0;i<10;i++)
    scanf("%d",&a[i]);

 ptr = a;           /* a=&a[0] */

 for(i=0;i<10;i++)
    {
    sum = sum + *ptr;    //*p=content pointed by 'ptr'
    ptr++;
    }

 printf("The sum of array elements is %d",sum);
}

Output :

Enter 10 elements : 11 12 13 14 15 16 17 18 19 20

The sum of array elements is 155

Explanation of Program :

Accept the 10 elements from the user in the array.
for(i=0;i<10;i++)
      scanf("%d",&a[i]);
We are storing the address of the array into the pointer.
ptr = a;
Now in the for loop we are fetching the value from the location pointer by pointer variable. Using De-referencing pointer we are able to get the value at address.
for(i=0;i<10;i++)
    {
    sum = sum + *ptr;
    ptr++;
    }
Suppose we have 2000 as starting address of the array. Then in the first loop we are fetching the value at 2000. i.e
sum = sum + (value at 2000)
    = 0   + 11
    = 11
In the Second iteration we will have following calculation -
sum = sum + (value at 2002)
    = 11  + 12
    = 23

No comments: