C program to find sum of array elements using recursion

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

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

 

I have already written an article “how to find the sum of the array of elements?“. You can also read this article for a better understanding.

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 recursion:

#include <stdio.h>

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


// Return sum of elements in A[0..N-1]
// using recursion.
int sumArrayElements(int arr[], const int N)
{
    if (N <= 0)
    {
        return 0;
    }
    return (sumArrayElements(arr, N - 1) + arr[N - 1]);
}

int main()
{
    int arr[] = { 1, 2, 3, 4, 5 };

    //calculate array size
    const int N = ARRAY_SIZE(arr);

    printf("%d\n", sumArrayElements(arr, N));

    return 0;
}

Output:

sum of array elements in C