C Program to Compute sum of the array elements using pointers !
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 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#include<stdio.h> #include<conio.h> void main() { int numArray[10]; int i, sum = 0; int *ptr; printf("\nEnter 10 elements : "); for (i = 0; i < 10; i++) scanf("%d", &numArray[i]); ptr = numArray; /* a=&a[0] */ for (i = 0; i < 10; i++) { sum = sum + *ptr; ptr++; } printf("The sum of array elements : %d", sum); } |
Output :
1 2 |
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.
1 2 |
for (i = 0; i < 10; i++) scanf("%d", &numArray[i]); |
We are storing the address of the array into the pointer.
1 |
ptr = numArray; /* a=&a[0] */ |
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.
1 2 3 4 |
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
1 2 3 |
sum = sum + (value at 2000) = 0 + 11 = 11 |
In the Second iteration we will have following calculation –
1 2 3 |
sum = sum + (value at 2002) = 11 + 12 = 23 |