This post helps us to find the sum of natural numbers using recursion using C programming.
C Program to Find the Sum of Natural Numbers using Recursion
#include<stdio.h> int recusum(int s); int main() { int num; printf("Enter a positive number:"); scanf("%d",&num); printf("sum=%d",recusum(num)); return 0; } //function calling process int recusum(int s) { if(s!=0) return s+recusum(s-1); else return s; }
Output
Explanation
This C program uses the recursion function, its the process of repeating items in a self-similar way, in simple words function calls itself. In this program, we initialize a function namely recusum(int s), and in the main function, we iterate a variable named num.
int recusum(int s); int main() { int num; printf("Enter a positive number:"); scanf("%d",&num); printf("sum=%d",recusum(num)); return 0; }
The function is called for the calculation and to get the desired result. Using the if-else condition we calculate the recursion value of the number entered by the user.
//function calling process int recusum(int s) { if(s!=0) return s+recusum(s-1); else return s; }
After the calculation part. we have now obtained the desired output.
Leave a Reply