











Program to Find Sum of Natural Numbers Using Recursion
Recursion :
Recursion is defined as calling the function by itself. It can be used when the solution depends on solutions to smaller instances of the same problem. Here we will use recursion to find sum of natural number.


Working of Program :
In the program, we will take a value and use recursion function to find the sum of natural number till the given value.
#include<stdio.h> // function to find sum int sum(int n) { if(n==0) return n; else{ return n + sum(n-1); } } int main(){ int num = 100; int answer = sum(num); printf(" The sum of first 100 number is : %d", answer); return 0; }
Output :
The sum of first 100 number is : 5050
What Happened Above?
In the Above Program, we take the value num and write the sum function sum which will add the numbers recursively and return it to the main function which will be the output of the program.
Example :
Let’s solve the same problem but this time we use the iterative method.
Run
#include<stdio.h> int main(){ int num = 100; int answer = 0; for(int i=0;i<=num;i++){ answer += i; } printf(" The sum of first 100 number is : %d", answer); return 0; }
Output :
The sum of first 100 number is : 5050
What Happened Above?
In the above program, we take the value of num and iterate the for loop from 0 to num and add them simultaneously during the iteration of for loop.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment