C Program to Find Sum of All Array Elements

  • Write a C program to find sum of array elements using for loop.
  • How to find sum of all elements of an array.

Required Knowledge

Algorithm to find sum of all array 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

C Program to Find Sum of All Array Elements

/*
* C Program to find sum of all array elements 
*/
#include <stdio.h>
#include <conio.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);
          
    getch();
    return 0;
}

Output

Enter Number of Elements in Array
5
Enter 5 numbers
1
2
3
4
5
Sum of All Array Elements : 15