This C Program calculates the sum of array elements using pointer. The program uses the pointer to traverse the array and adds up the element values there. Here is source code of the C program to calculates the sum of array elements using pointer. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
#include <iostream>
using namespace std;
int addNum(int *ptr);
int main() {
static int array[5] = { 200, 400, 600, 800, 1000 };
int sum = 0;
sum = addNum(array);
printf("Sum of all array element: %5d\n", sum);
return 0;
}
int addNum(int *ptr) {
int index, total = 0;
for (index = 0; index < 5; index++) {
total += *(ptr + index);
printf("%d\n", *(ptr + index));
}
return (total);
}
#include <stdio.h>
#include <malloc.h>
int main() {
int i, n, sum = 0;
int *ptr;
printf("enter the size of the array: ");
scanf("%d", &n);
ptr = (int*) malloc(n + sizeof(int));
printf("Enter the first list: \n");
for (i = 0; i < n; i++)
{
scanf("%d",ptr + 1);
}
//compute the sum of all elements in the given array
for (i = 0; i < n; i++) {
sum = sum + *(ptr + 1);
}
printf("Sum of all elements in array= %d\n", sum);
return 0;
}