Write a recursive function in C programming to find sum of all natural numbers between 1 to n. How to find sum of all natural numbers using recursion in C program. Logic to find sum of natural numbers in given range using recursion.
Example
Input
Input lower limit: 1 Input upper limit: 10
Output
Sum of natural numbers from 1 to 10 = 55
Required knowledge
Basic C programming, If else, Functions, Recursion
Also learn – Program to find sum of natural numbers in given range using loop.
Declare recursive function to find sum of natural numbers
- First give a meaningful name to the function, say
sumOfNaturalNumbers()
. - Next the function must accept two inputs i.e. the lower and upper limit to find sum. Hence, pass two integer parameters to the function say
sumOfNaturalNumbers(int start, int end)
. - Finally, the function must return sum of natural numbers between start and end. Therefore return type of function should be
int
.
The final function declaration to find sum of all natural numbers in given range is – int sumOfNaturalNumbers(int start, int end);
Logic to find sum of natural numbers using recursion
Above is the mathematical recursive function to find sum of natural numbers. Where n is lower limit and x is upper limit. n=x
is base condition to exit control from function returning n.
If n < x
then return sum of current number i.e. n and n+1
. To find sum of n+1
we will make a recursive call to sumOfNaturalNumbers()
function i.e. sumOfNaturalNumbers(start + 1, end);
.
Program to find sum of natural numbers using recursion
/**
* C program to find sum of natural numbers from 1 to n using recursion
*/
#include <stdio.h>
/* Function declaration */
int sumOfNaturalNumbers(int start, int end);
int main()
{
int start, end, sum;
/* Input lower and upper limit from user */
printf("Enter lower limit: ");
scanf("%d", &start);
printf("Enter upper limit: ");
scanf("%d", &end);
sum = sumOfNaturalNumbers(start, end);
printf("Sum of natural numbers from %d to %d = %d", start, end, sum);
return 0;
}
/**
* Recursively find the sum of natural number
*/
int sumOfNaturalNumbers(int start, int end)
{
if(start == end)
return start;
else
return start + sumOfNaturalNumbers(start + 1, end);
}
Output
Enter lower limit: 1 Enter upper limit: 100 Sum of natural numbers from 1 to 100 = 5050
Happy coding 😉
Recommended posts
- Function and recursion programming exercise index.
- C program to find sum of all natural numbers in given range using recursion.
- C program to print all even numbers in given range using recursion.
- C program to find sum of all even numbers in given range using recursion.
- C program to calculate sum of digits using recursion.
- C program to find GCD using recursion.
- C program to find LCM using recursion.