Example:
Input elements: 10, 20, 30, 40, 50
Sum of all elements = 150
Required knowledge
Basic C programming, For loop, ArrayYou may also find interesting to learn how to sum array elements using recursion.
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; /* * Reads size and elements in array from user */ printf("Enter size of the array: "); scanf("%d", &n); printf("Enter %d elements in the array: ", n); for(i=0; i<n; i++) { scanf("%d", &arr[i]); } /* * Adds each element of array 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.
/** * 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; /* * Reads size and elements in array from user */ printf("Enter size of the array: "); scanf("%d", &n); printf("Enter %d elements in the array: ", n); for(i=0; i<n; i++) { scanf("%d", &arr[i]); // Adds each element of array 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
Enter 10 elements in the array : 10 20 30 40 50 60 70 80 90 100
Sum of all elements of array = 550
Note: sum += arr[i] is similar to sum = sum + arr[i]. You could use any of them.
Happy coding ;)
You may also like
- Array and matrix programming exercises index.
- C program to read and print all elements of array.
- C program to find sum of all even numbers between 1 to n.
- C program to find sum of all odd numbers between 1 to n.
- C program to find sum of all Prime numbers between 1 to n.
- C program to find maximum and minimum elements in an array.
- C program to insert an element in array at specified position.
- C program to delete an element from array at specified position.
- C program to delete all duplicate elements from an array.
- C program to find all unique elements in an array.
- C program to count frequency of each element in an array.