Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to calculate the sum of all elements of an array.

C Code Example — Array Programs

ADVERTISEMENT

C Program to calculate the sum of all elements of an array.

Objective

Write a C program to calculate the sum of all elements in an array.

Algorithm / Approach

  1. Declare an array a[5] and initialize sum = 0.
  2. Use a for loop to read 5 integers from the user into the array.
  3. Use a second for loop to iterate through the array elements.
  4. Inside the second loop, add each element to the sum: sum = sum + a[i].
  5. Print the final sum.
main.c
#include<stdio.h>
int main( ) {
 int i,sum=0;
 int a[5];
 printf("Enter 5 elements : ");
 for(i=0; i < 5; i++) {
  scanf("%d",&a[i]);
 }
 for(i=0; i < 5; i++) {
  sum = sum +a[i];
 }
 printf("SUM = %d",sum);
 return 0;
}

Expected Output

Enter 5 elements : 10 20 30 25 35
SUM = 120

Explanation of the Program

  • An array is a collection of variables of the same type stored in contiguous memory locations.
  • In C, array indices start at 0. So an array of size 5 has elements at indices 0, 1, 2, 3, and 4.
  • It is standard practice to use a for loop to traverse arrays because the loop counter i directly maps to the array index.

Complexity

Time Complexity O(n) - Where n is the size of the array.
Space Complexity O(n) - To store the array elements in memory.
ADVERTISEMENT