C++ Program to Find Sum of Natural Numbers Using Recursion

In the previous article, we have discussed C++ program to Check Whether a Number can be Split into Sum of Two Prime Numbers. In this article, we will see C++ Program to Find Sum of Natural Numbers Using Recursion.

C++ Program to Find Sum of Natural Numbers Using Recursion

  • How to find sum of natural numbers using recursion in C++.
  • Write a C++ program to find sum of all natural numbers using recursion.

C++ program to calculate sum of all natural numbers using recursion

C++ program to calculate sum of all natural numbers using recursion

#include<iostream>
 
using namespace std;
 
int getSum(int N);
int main() {
    int n;
    cout << "Enter an Integer\n";
    cin >> n;
     
    cout << "Sum of Numbers from 1 to " << n << " = " << getSum(n);
    return 0;
}
 
int getSum(int N) {
    if(N >= 1)
        return N + getSum(N-1);
    else
        return 0;
}

Output

Enter an Integer
10
Sum of Numbers from 1 to 10 = 55

Learn and explore basic C++ Practice Programs that help to enhance your skills & knowledge of the programming language. Get to know how to write simple and clear code on this page.