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

C++ program to find 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

Recommended Posts
C++ Program to Find Sum of Natural Numbers
C++ Program to Calculate Average Percentage Marks
C++ Program to Find Quotient and Remainder
C++ Program to Make a Simple Calculator
C++ Program to Convert Temperature from Celsius to Fahrenheit
C++ Program to print ASCII Value of All Alphabets
C++ Program to check Whether a Number is Palindrome or Not
C++ Program to Find Largest Element of an Array
C++ Program to Find Smallest Element in Array
All C++ Programs