OverIQ.com

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
}

Try it now

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 #

  1. We start by declaring variables arr and sum to store the array and the sum respectively. Note that the variable sum is initialized to 0.
  2. In lines 14-18, we have a loop which prompts the user to enter elements into the array.
  3. In lines 21-24, we have a second for loop to sum the elements of an array.
  4. In line 25, we print the sum using the print statement.

Recommended Reading: