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.

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>

int main()
    int arr[100];
    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 += arr[i];

    printf("Sum of all elements of array = %d", sum);

    return 0;

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 ;)

Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment