C Programming Example to find sum of array elements - 2 Examples

Algorithm


  1. Initialize an empty array
  2. Take number of items in array, n
  3. Loop upto n and take value
  4. Assign value to the index of that array
  5. Initialize a sum = 0
  6. loop upto n and make sum = sum + array [index]
  7. Print Sum

Code Examples

#1 Code Example with C Programming

Code - C Programming

#include <stdio.h>

int main()
{
    int array[1000], i, n, sum = 0;
   
    printf("Enter size of the array : ");
    scanf("%d", &n);
 
    printf("Enter elements in array : ");
    for(i = 0; i < n; i++)
    {
        scanf("%d", &array[i]);
    }
    
    for(i=0; i < n; i++)
    { 
        sum += array[i];
    }
    
    printf("Sum = %d", sum);
    return 0;
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
Enter size of the array : 5
Enter elements in array : 1 2 3 4 5

Output

x
+
cmd
Sum = 15

#2 C Program to find sum of array elements using Function

Code - C Programming

#include <stdio.h>

int sumOfArray(int array[], int n) {
    int i = 0, sum = 0;
    
    for(i=0; i < n; i++)
    { 
        sum += array[i];
    }
    
    return sum;
}

int main()
{
    int array[1000], i, n;
   
    printf("Enter size of the array : ");
    scanf("%d", &n);
 
    printf("Enter elements in array : ");
    for(i = 0; i < n; i++)
    {
        scanf("%d", &array[i]);
    }
    
    printf("Sum = %d", sumOfArray(array, n));
    return 0;
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
Enter size of the array : 6
Enter elements in array : 1 2 3 4 5 6

Output

x
+
cmd
Sum = 21

Demonstration


C Programming Example to find sum of array elements, c program to find sum of array, c program array sum, array sum in c programming