
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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);
- Related Questions & Answers
- Java 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
- C++ Program to Calculate Sum of Natural Numbers
- Program to find sum of first n natural numbers in C++
- C++ Program to Find Fibonacci Numbers using Recursion
- Java program to find the sum of n natural numbers
- How to Find the Sum of Natural Numbers using Python?
- 8085 program to find the sum of first n natural numbers
- Sum of first n natural numbers in C Program
- C# program to find the sum of digits of a number using Recursion
- C Program for cube sum of first n natural numbers?
- C++ Program for cube sum of first n natural numbers?
- Java Program to Calculate the Sum of Natural Numbers
- C++ Program for Sum of squares of first n natural numbers?
Advertisements