
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
C++ program to Find Sum of Natural Numbers using Recursion
The natural numbers are the positive integers starting from 1.
The sequence of natural numbers is −
1, 2, 3, 4, 5, 6, 7, 8, 9, 10……
The program to find the sum of first n natural numbers using recursion is as follows.
Example
#include <iostream> using namespace std; int sum(int n) { if(n == 0) return n; else return n + sum(n-1); } int main() { int n = 10; cout<<"Sum of first "<<n<<" natural numbers is "<<sum(n); return 0; }
Output
Sum of first 10 natural numbers is 55
In the above program, the function sum() is a recursive function. If n is 0, it returns 0 as the sum of the first 0 natural numbers is 0. If n is more than 0, then sum recursively calls itself itself with the value n-1 and eventually returns the sum of n, n-1, n-2…...2,1. The code snippet that demonstrates this is as follows.
int sum(int n) { if(n == 0) return n; else return n + sum(n-1); }
In the function main(), the sum of the first n natural numbers is displayed using cout. This can be seen as follows −
cout<<"Sum of first "<<n<<" natural numbers is "<<sum(n);
- Related Articles
- Java Program to Find the Sum of Natural Numbers using Recursion
- Golang Program to Find the Sum of Natural Numbers using Recursion
- How to Find Sum of Natural Numbers Using Recursion in Python?
- Java Program to Find Sum of N Numbers Using Recursion
- Golang Program to Find the Sum of N Numbers using Recursion
- Java program to find the sum of n natural numbers
- C++ Program to Find Fibonacci Numbers using Recursion
- How to Find the Sum of Natural Numbers using Python?
- 8085 program to find the sum of first n natural numbers
- Program to find sum of first n natural numbers in C++
- C++ Program to Calculate Sum of Natural Numbers
- Python Program to Find the Product of two Numbers Using Recursion
- Java Program to Find the Product of Two Numbers Using Recursion
- Golang Program to Find the Product of Two Numbers Using Recursion
- C++ Program to Find the Product of Two Numbers Using Recursion

Advertisements