Google News
logo
C++ program to Find Sum of Natural Numbers using Recursion
In the following example of C++ program to find the sum of natural numbers up to a given number using recursion :
Program :
#include <iostream>
using namespace std;

int sum(int n) {
    if (n == 0) {
        return 0;
    } else {
        return n + sum(n - 1);
    }
}

int main() {
    int n;

    cout << "Enter a positive integer: ";
    cin >> n;

    cout << "The sum of natural numbers up to " << n << " is " << sum(n) << endl;

    return 0;
}
Output :
Enter a positive integer: 20
The sum of natural numbers up to 20 is 210
* This program defines a recursive function called sum that takes a positive integer n as its argument. If n is 0, the function returns 0; otherwise, it returns n plus the result of calling sum(n - 1).

* In main(), the user is prompted to enter a positive integer, and the sum function is called with that integer as its argument. The result is then printed out.