Write C program to find sum of array elements

In this blog post, we learn how to write a C program to find the sum of array elements? So here will write the C program to find the sum of array elements. We will also see how to display the sum of array elements.

So let’s see the logic to calculate the sum of the array elements. Suppose arr is an integer array of size N (arr[N] ), the task is to write the C Program to sum the elements of an array.

Examples,

Input : arr[] = {1, 2, 3}
Output : (1+2+3) => 6


Input : arr[] = {15, 12, 13, 10}
Output: (15 + 12 + 13+ 10) => 50

 

 

Logic to calculate the sum of the array elements:

1. Create an intermediate variable ‘sum’.

2. Initialize the variable ‘sum’ with 0.

3. To find the sum of all elements, iterate through each element, and add the current element to the sum.

//Logic within the loop

sum = sum + arr[i];

where i is the index of the array.

 

 

C program to find the sum of array elements:

 

#include <stdio.h>

//Calculate array size
#define ARRAY_SIZE(a)  sizeof(a)/sizeof(a[0])

int main()
{
    int arr[] = {15, 12, 13, 10};
    int sum = 0;  // accumulate sum in this variable
    int i = 0;

    // length of the array
    int N = ARRAY_SIZE(arr);

    // loop from index 0 to N
    for(i = 0; i < N; i++)
    {
        sum += arr[i];  // add the current element to sum
    }

    printf("\nSum = %d", sum);

    return 0;
}

Output:

sum of array elements in C

 

 

If you want to learn more about the c language, here 10 Free days (up to 200 minutes) C video course for you.

Your free trial is waiting

 

C program to find the sum of array elements using functions:

We can also calculate the sum of array elements using the function. Here I am creating a small function with the name ‘sumArrayElements’.  In this function, I am passing the array and the size of the array as a parameter and returning the sum of the array elements.

 

#include <stdio.h>

//Calculate array size
#define ARRAY_SIZE(a)  sizeof(a)/sizeof(a[0])


int sumArrayElements(int arr[], const int n)
{
    int sum = 0;  // accumulate sum in this variable
    int i;

    // Iterate through all elements
    // and add them to sum
    for (i = 0; i < n; i++)
    {
        sum += arr[i];
    }
    return sum;
}


int main()
{
    int arr[] = {15, 12, 13, 10};

    // length of the array
    const int N = ARRAY_SIZE(arr);

    const int sum =  sumArrayElements(arr,N);

    printf("\nSum = %d", sum);

    return 0;
}

Output:

Sum = 50

 

Recommended Articles for you:

14 comments

Leave a Reply

Your email address will not be published. Required fields are marked *