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.

Sum 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.

Run

#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

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

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

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription