Google News
logo
C Program to Find Sum of Array Elements
We will see the following three programs to add the elements of an array.

1) Find sum of elements using simple loops.
2) Using recursion.
3) Using pointers.

Example 1: Program to find sum of array elements using loops


In this program we are using for loop to find the sum of array elements.
Program :
#include <stdio.h>
int main()
{
  int arr[100],size,sum=0;

  printf("Enter size of the array: ");
  scanf("%d",&size);

  printf("Enter the elements of the array: ");
  for(int i=0; i<size; i++)
  {
    scanf("%d",&arr[i]);
  }
  //calculating sum of entered array elements
  for(int i=0; i<size; i++)
  {
    sum+=arr[i];
  }
  printf("Sum of array elements is: %d",sum);

  return 0;
}
Output :
Enter size of the array: 5
Enter the elements of the array: 7
12
26
31
45
Sum of array elements is: 121


Example 2: Sum of array elements using Recursion


This program calls the user defined function sum_array_elements() and the function calls itself recursively.
Program :
#include <stdio.h>
int sum_array_elements( int arr[], int n ) {
  if (n < 0) {
    //base case:
    return 0;
  } else{
    //Recursion: calling itself
    return arr[n] + sum_array_elements(arr, n-1);
  }
}
int main()
{
  int array[] = {1,22,31,14,35,47,39};
  int sum;
  sum = sum_array_elements(array,6);
  printf("Sum of array elements is: %d",sum);
  return 0;
}
Output :
Sum of array elements is: 189


Example 3: Sum of array elements using pointers

Here we are setting up the pointer to the base address of array and then we are incrementing pointer and using * operator to get & add the values of all the array elements.

#include<stdio.h>
int main()
{
   int array[5];
   int i, sum=0;
   int *ptr;

   printf("\nEnter array elements (5 integer values):");
   for(i=0;i<5;i++)
      scanf("%d",&array[i]);

   /* array is equal to base address
    * array = &array[0] */
   ptr = array;

   for(i=0;i<5;i++) 
   {
      //*ptr refers to the value at address
      sum = sum + *ptr;
      ptr++;
   }

   printf("\nThe sum is: %d",sum);
}​


Output :

Enter array elements (5 integer values):7
9
12
17
25
The sum is: 70