Quantcast
Channel: C Programming Archives - QnA Plus
Viewing all articles
Browse latest Browse all 93

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

$
0
0

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;
}

The post C Program to Calculate the Sum of All Elements in an Array appeared first on QnA Plus.


Viewing all articles
Browse latest Browse all 93

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>