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
- Declare an array
a[5]and initializesum = 0. - Use a
forloop to read 5 integers from the user into the array. - Use a second
forloop to iterate through the array elements. - Inside the second loop, add each element to the sum:
sum = sum + a[i]. - 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
forloop to traverse arrays because the loop counteridirectly 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.