C program to find sum of all elements of an array

Write a C program to read elements in an array and find the sum of all elements of the array. C program to find sum of elements of the array. How to add elements of an array using for loop in C programming.

Example:
Input elements: 10, 20, 30, 40, 50
Sum of all elements = 150

Required knowledge

Basic C programming, For loop, Array

You 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

Note: sum += arr[i] is similar to sum = sum + arr[i]. You could use any of them.

Happy coding ;)


You may also like

Labels: , ,