C Program to sum the elements of an array
Last updated on September 23, 2020
The following is a C program to find the sum of elements of an array:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | /**********************************************
Program to sum the elements of an array
**********************************************/
#include<stdio.h> // include stdio.h library
#define MAX 5
int main(void)
{
int arr[MAX];
int sum = 0; // accumulate sum in this variable
// read input
for(int i = 0; i < MAX; i++)
{
printf("Enter a[%d]: ", i);
scanf("%d", &arr[i]);
}
// loop from index 0 to MAX
for(int i = 0; i < MAX; i++)
{
sum += arr[i]; // add the current element to sum
}
printf("\nSum = %d", sum);
return 0; // return 0 to operating system
}
|
Expected Output:
1 2 3 4 5 6 7 | Enter a[0]: 1
Enter a[1]: 2
Enter a[2]: 3
Enter a[3]: 4
Enter a[4]: 5
Sum = 15
|
How it works #
- We start by declaring variables
arr
andsum
to store the array and the sum respectively. Note that the variablesum
is initialized to0
. - In lines 14-18, we have a loop which prompts the user to enter elements into the array.
- In lines 21-24, we have a second for loop to sum the elements of an array.
- In line 25, we print the sum using the print statement.
Recommended Reading:
- C Program to reverse the elements of an array
- C Program to find the maximum and minimum element in the array
Load Comments