Here we will see the program to find sum of first n natural numbers using recursion.
First we will take input the value on n from the user ,and then we will call the function and that function will return the sum to the main function.
Program:
#include <iostream>
using namespace std;
int sum(int n)  //function for finding sum
{
    if(n == 1)
    return n;
    
    return n + sum(n -1);  //recursive calling the function till n becomes 1
}
int main()
{
    int n;
    cout << "Enter value of n: ";
    cin >> n;
    
    cout << "Sum of first " << n << " natural number is: " << sum(n);   //function call
    return 0;
}
Output:
Enter value of n: 5
Sum of first 5 natural number is: 15
C++ Program to Find Sum of First n Natural Numbers using Recursion
 Reviewed by Beast Coder
        on 
        
February 26, 2021
 
        Rating:
 
        Reviewed by Beast Coder
        on 
        
February 26, 2021
 
        Rating: 
       Reviewed by Beast Coder
        on 
        
February 26, 2021
 
        Rating:
 
        Reviewed by Beast Coder
        on 
        
February 26, 2021
 
        Rating: 

 
 
 

No comments: