Program to Find Sum of N natural numbers in c using recursion | Sum of Natural Numbers using recursion in C
Here we are going to write a program to find sum of n natural numbers in c using recursion. This is a very simple program. We can do this normally also without recursion that is just c program to find sum of n natural numbers. Also this program can be done using function, c program to find sum of natural numbers using function. But here we will do this program using recursive method. Before writing code lets understand what is Recursion.
What is Recursion?
Recursion occurs when a function calls itself within a function as a result it is called repeatedly. It solves smaller subproblems of original problem.
** Sum of N natural numbers formula - n(n+1)/2
You can remember this formula but it is not needed for program using recursion.
Lets code it.
Program to Find Sum of N natural numbers in c using recursion
#include <stdio.h>
int sm(int n){
if(n==0) return 0;
else return (n + sm(n-1));
}
int main(){
int n;
printf("Enter number of terms: ");
scanf("%d",&n);
printf("Sum : %d",sm(n));
return 0;
}Output
Enter number of terms: 5
Sum : 15More like this

Post a Comment
If you have any doubts, please let me know