Here is the C program to find sum of array elements using for loop.
Required Knowledge
Algorithm to find sum of all array elements
Let inputArray is an integer array having N elements.
Let inputArray is an integer array having N elements.
- Declare an integer variable 'sum' and initialize it to 0. We will use 'sum' variable to store sum of elements of array.
- Using for loop, we will traverse inputArray from array from index 0 to N-1.
- For any index i (0<= i <= N-1), add the value of element at index i to sum.
sum = sum + inputArray[i]; - After termination of for loop, sum will contain the sum of all array elements.
C program to find the sum of all array elements using for loop
#include <stdio.h> int main(){ int inputArray[500], elementCount, counter, sum = 0; printf("Enter Number of Elements in Array\n"); scanf("%d", &elementCount); printf("Enter %d numbers \n", elementCount); /* Read array elements */ for(counter = 0; counter < elementCount; counter++){ scanf("%d", &inputArray[counter]); } /* Add array elements */ for(counter = 0; counter < elementCount; counter++){ sum += inputArray[counter]; } printf("Sum of All Array Elements : %d", sum); return 0; }Output
Enter Number of Elements in Array 5 Enter 5 numbers 1 2 3 4 5 Sum of All Array Elements : 15
Related Topics