Open In App

C++ Program For Sum of Natural Numbers Using Recursion

Improve
Improve
Like Article
Like
Save
Share
Report

Natural numbers include all positive integers from 1 to infinity. It does not include zero (0). Given a number n, find the sum of the first n natural numbers. To calculate the sum, we will use the recursive function recur_sum().

Sum of first N numbers

 

Examples: 

Input: 3
Output: 6
Explanation: 1 + 2 + 3 = 6

Input: 5
Output: 15
Explanation: 1 + 2 + 3 + 4 + 5 = 15

The Sum of Natural Numbers Using Recursion

Below is a C++ program to find the sum of natural numbers up to n using recursion:

C++




// C++ program to find the sum
// of natural numbers up to n
// using recursion
#include <iostream>
using namespace std;
 
// Returns sum of first
// n natural numbers
int recurSum(int n)
{
    if (n <= 1)
        return n;
 
    return n + recurSum(n - 1);
}
 
// Driver code
int main()
{
    int n = 5;
    cout << recurSum(n);
 
    return 0;
}


Output

15

Last Updated : 23 Jun, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads