Array Exercises
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.
Required knowledge
Basic C programming, c-Arrays, C Loops
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.
- Input size and elements in array, store in some variable say n and arr[n].
- To store sum of array elements, initialize a variable sum = 0. Note: sum must be initialized only with 0.
- 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++).
- 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.
Read more - Program to find sum of array elements using recursion
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; }