In this section, we will write a C program to perform the addition of all elements in Array.
Before we start, if you want to learn about the Arrays as this program uses an array, click the link below.
Program:
Take the user input for the elements of an array and then by iterating the loop, add each of the element present in an array at each iteration.
Example:
Input: arr[] = {1, 2, 3}
loop: 1 + 2 + 3 = 6
Output: 6
We will write two different programs in C to sum the elements in an array.
- Standard method
- Using function (user-defined function)
C Program to find the sum of all elements present in an Array
This is a standard method where all of the calculation is done within the main function.
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 | #include <stdio.h> int main() { int arr[100], i, size, sum = 0; printf("Enter size of an array: "); scanf("%d", &size); printf("Enter %d elements in an array:\n", size); for (i = 0; i < size; i++) { scanf("%d", &arr[i]); } for (i = 0; i < size; i++) { //adding each of the element sum += arr[i]; } printf("Sum of the element of an array: %d", sum); return 0; } |
Output:
Enter size of an array: 5
Enter 5 elements in an array:
5
10
6
20
3
Sum of the element of an array: 44
C Program to find the sum of all elements present in an Array using function
A separate function (array_sum()
) is created and the parameter array (arr
), and the size of an array (size
) is passed.
The function calculates the sum of all elements and returns the total sum to the main function where it is displayed.
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 30 31 | #include <stdio.h> int array_sum(int arr[], int size) { int i, sum = 0; for (i = 0; i < size; i++) { sum += arr[i]; } return sum; } int main() { int arr[100], i, size, result; printf("Enter size of an array: "); scanf("%d", &size); printf("Enter %d elements in an array:\n", size); for (i = 0; i < size; i++) { scanf("%d", &arr[i]); } result = array_sum(arr, size); printf("Sum of the element of an array: %d", result); } |
Output:
Enter size of an array: 4
Enter 5 elements in an array:
5
10
3
8
Sum of the element of an array: 26