- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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);
Advertisements