C Program to Calculate the Sum of All Elements in an Array

Here is the C program that prints the sum of all elements in an array.

#include <stdio.h>

int main(){
  
  int arr[] = {23, 45, 1, 34, 56, 76, 74};
  int i = 0, sum = 0;
  int len = sizeof(arr)/sizeof(int);
  
  for(i = 0; i < len; i++) {
    sum += arr[i];
  }
  
  printf("Sum of all elements in the array: %d\n", sum);
  
  return 0;
}

Output of this program:

Sum of all elements in the array: 309

This program is good enough solution. If you are interested, you can see few other solutions in the following sections.

Recursive Version

We can wire a recursive function for the same purpose.

#include <stdio.h>

int sum(int *arr, int n) {
  if (n == 0) return arr[0];
  
  return arr[n] + sum(arr, n-1);
}

int main(){
  
  int arr[] = {23, 45, 1, 34, 56, 76, 74};
  int result = 0;
  
  result = sum(arr, sizeof(arr)/sizeof(int) - 1);
  
  printf("Summ of all elements in the array: %d\n", result);
  
  return 0;
}

Divide and Conquer

We can apply divide and conquer method also.

#include <stdio.h>

int sum(int *arr, int start, int end) {
  int mid;
  
  if (start == end) return arr[start];
  
  mid = (start + end) / 2;
  
  return sum(arr, start, mid) + sum(arr, mid+1, end);
}

int main(){
  
  int arr[] = {23, 45, 1, 34, 56, 76, 74};
  int result = 0;
  
  result = sum(arr, 0, sizeof(arr)/sizeof(int) - 1);
  
  printf("Summ of all elements in the array: %d\n", result);
  
  return 0;
}

Author: Srikanta

I write here to help the readers learn and understand computer programing, algorithms, networking, OS concepts etc. in a simple way. I have 20 years of working experience in computer networking and industrial automation.


If you also want to contribute, click here.

Leave a Reply

Your email address will not be published. Required fields are marked *

0
0
0
0
0
0