C++ Program to Find Sum of Natural Numbers using Recursion
ADVERTISEMENTS
C++ program to find sum of natural numbers using recursion. In this program, you will learn how to find the sum of natural numbers using recursion.
Take an example to find the sum through a c++ program:
// C++ Program to Find Sum of Natural Numbers using Recursion
#include <bits/stdc++.h>
using namespace std;
int recSum(int x);
// It's the driver function
int main() {
int x;
// x - denotes a positive number
cout << "-----Enter a positive number to get the sum-----\n";
cin >> x;
cout << "\nThe Sum is: " << recSum(x) << "\n";
return 0;
}
// It's the recrsive function
// To make the sum of natural numbers
int recSum(int n) {
if (n)
return n + recSum(n - 1);
else
return n;
}
Output
-----Enter a positive number to get the sum-----
22
The Sum is: 253