Sum of elements in array using pointers
C program to print sum of numbers in array using pointers.
Program
#include<stdio.h>
#include<conio.h>
#define MAX 50
void main()
{
int arr[MAX];
int n, i, sum;
int *ptr;
printf("Enter the size of the array\t:");
scanf("%d",&n);
printf("\nEnter elements in the array\n");
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
ptr = arr;
sum = 0;
for(i=0;i<n;i++)
{
sum = sum + *ptr;
ptr++;
}
printf("\nSum of the elements of the array\t:%d",sum);
getch();
}
Output
Enter the size of the array :5
Enter elements in the array
1
2
3
4
5
Sum of the elements of the array :15
Explanation
In the above program, an integer array 'arr' is declared and a pointer variable 'ptr' is also declared.
ptr = arr, ptr points to arr[0] element of the array.
We have to calculate the sum of the elements of the array. 'sum' is initialized to 0, to avoid garbage value addition.
*ptr gives the value at the location to which it is pointing.
Initially, it points to arr[0]. So, this value is added to 'sum' variable.
Now, Pointer 'ptr' is incremented by 1, so that, it point to the next element of the array 'arr[1]'.
Now, the value at arr[1] is added to the previously calculated sum and stored in the variable 'sum'
The above procedure is repeated for all the elements of the array.
ptr = arr, ptr points to arr[0] element of the array.
We have to calculate the sum of the elements of the array. 'sum' is initialized to 0, to avoid garbage value addition.
for(i=0;i<n;i++)
{
sum = sum + *ptr;
ptr++;
}
*ptr gives the value at the location to which it is pointing.
Initially, it points to arr[0]. So, this value is added to 'sum' variable.
Now, Pointer 'ptr' is incremented by 1, so that, it point to the next element of the array 'arr[1]'.
ptr++;
Now, the value at arr[1] is added to the previously calculated sum and stored in the variable 'sum'
The above procedure is repeated for all the elements of the array.