Write a C program to find sum of array elements using recursion. C program to read elements in an array and find sum of array elements using recursion. How to find sum of elements of array using recursive function in C programming.
Example:
Input size of array: 10
Input array elements: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Output sum of array: 55
Happy coding ;)
Example:
Input size of array: 10
Input array elements: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Output sum of array: 55
Required knowledge
Basic C programming, Array, Function, RecursionLogic to find sum of array elements using recursion
We have already seen how easily we can find sum of elements of array using loops and many more similar programs based on array. Here we will be using the concept of recursion to find sum of elements of array. Before getting more depth in this program I assume that you must know how to print elements of array using recursion. Logic to this program is similar as of the previous program to print array elements using recursion.Program to print sum of array using recursion
/**
* C program to find sum of elements of array using recursion
*/
#include <stdio.h>
#define MAX_SIZE 100
/* Function declaration to find sum of array */
int sum(int arr[], int start, int len);
int main()
{
int arr[MAX_SIZE];
int N, i, sumofarray;
/*
* Reads size and elements in array
*/
printf("Enter size of the array: ");
scanf("%d", &N);
printf("Enter elements in the array: ");
for(i=0; i<N; i++)
{
scanf("%d", &arr[i]);
}
sumofarray = sum(arr, 0, N);
printf("Sum of array elements: %d", sumofarray);
return 0;
}
/**
* Recursively finds the sum of elements in an array.
*/
int sum(int arr[], int start, int len)
{
if(start >= len)
return 0;
return (arr[start] + sum(arr, start+1, len));
}
Output
Enter size of the array: 10
Enter elements in the array: 1 2 3 4 5 6 7 8 9 10
Sum of array elements: 55
Enter elements in the array: 1 2 3 4 5 6 7 8 9 10
Sum of array elements: 55
Happy coding ;)
You may also like
- Function and recursion programming exercises index.
- C program to find power of any number using recursion.
- C program to find reverse of a given number using recursion.
- C program to check palindrome number using recursion.
- C program to find sum of digits using recursion.
- C program to find factorial of any given number using recursion.
- C program to generate Fibonacci series using recursion.
- C program to find GCD(HCF) of any two given numbers using recursion.
- C program to find LCM of any two numbers using recursion.
- C program to check even or odd number using functions.
- C program to find maximum and minimum between two numbers using functions.