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.
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:
Recommended Articles for you:
- Best gift for programmers.
- Best electronic kits for programmers.
- Write C program to find the sum of array elements
- C Program to reverse the elements of an array
- C Program to find the maximum and minimum element in the array
- Calculate size of an array in without using sizeof in C
- How to create a dynamic array in C?
- How to access 2d array in C?
- A brief description of the pointer in C.
- Dangling, Void, Null and Wild Pointers
- Function pointer in c, a detailed guide
- How to use the structure of function pointer in c language?
- Memory Layout in C.
- 100 C interview Questions
- File handling in C.
- C format specifiers.