Skip to content

Instantly share code, notes, and snippets.

@wohhie
Last active October 15, 2016 04:55
Show Gist options
  • Save wohhie/20d43901903c5f5a553b044b83100329 to your computer and use it in GitHub Desktop.
Save wohhie/20d43901903c5f5a553b044b83100329 to your computer and use it in GitHub Desktop.
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 …
#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;
}
#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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment