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

situs togel

situs togel

slot gacor hari ini

toto slot

situs toto

situs gacor

situs gacor

slot gacor

situs gacor

situs gacor

situs toto

situs toto

kampungbet

kampungbet

situs togel

situs togel

kampungbet

kampungbet

slot online

slot online

slot online

kampungbet

kampungbet

kampungbet

slot gacor

kampungbet

situs togel

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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