C program to find sum of array elements

Write a C program to read elements in an array and find the sum of array elements. C program to find sum of elements of the array. How to add elements of an array using for loop in C programming. Logic to find sum of array elements in C programming.

Example

Input

Input elements: 10, 20, 30, 40, 50

Output

Sum of all elements = 150

Logic to find sum of array elements

Finding sum of array elements is easy when you know how to iterate through array elements. In this post I will explain two approaches to find sum of array elements. First let us begin with the easiest approach.

1. Input size and elements in array, store in some variable say n and arr[n].
2. To store sum of array elements, initialize a variable sum = 0. Note: sum must be initialized only with 0.
3. To find sum of all elements, iterate through each element and add the current element to the sum. Which is run a loop from 0 to n. The loop structure should look like for(i=0; i<n; i++).
4. Inside the loop add the current array element to sum i.e. sum = sum + arr[i] or even you can do sum += arr[i].

Program to find sum of array elements

/**
* C program to find sum of all elements of array
*/

#include <stdio.h>
#define MAX_SIZE 100

int main()
{
int arr[MAX_SIZE];
int i, n, sum=0;

/* Input size of the array */
printf("Enter size of the array: ");
scanf("%d", &n);

/* Input elements in array */
printf("Enter %d elements in the array: ", n);
for(i=0; i<n; i++)
{
scanf("%d", &arr[i]);
}

/*
* Add each array element to sum
*/
for(i=0; i<n; i++)
{
sum = sum + arr[i];
}

printf("Sum of all elements of array = %d", sum);

return 0;
}

Note: You can also re-write this program using a shorter and efficient approach using single for loop as written below.

Program to find sum of array elements - best approach

/**
* C program to find sum of all elements of array
*/

#include <stdio.h>
#define MAX_SIZE 100

int main()
{
int arr[MAX_SIZE];
int i, n, sum=0;

/* Input size of the array */
printf("Enter size of the array: ");
scanf("%d", &n);

/* Input elements in array */
printf("Enter %d elements in the array: ", n);
for(i=0; i<n; i++)
{
scanf("%d", &arr[i]);

// Add each array element to sum
sum += arr[i];
}

printf("Sum of all elements of array = %d", sum);

return 0;
}

Output

Enter size of the array: 10
Enter 10 elements in the array : 10 20 30 40 50 60 70 80 90 100
Sum of all elements of array = 550

Note: I have used shorthand assignment operator in sum += arr[i] which is equivalent to sum = sum + arr[i]. You could use any of them. 