
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Natural numbers are positive numbers starting from 1, such as 1, 2, 3, and so on. Here, we will take a positive number n as input and and then will find the sum of all natural numbers from 1 up to n using recursion using C++ program.
Example
Input: n = 5 The sum of the first 5 natural numbers is: 1 + 2 + 3 + 4 + 5 = 15 Output: 15 Input: n = 8 The sum of the first 8 natural numbers is: 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 = 36 Output: 36
Using Recursion to Calculate Sum
To calculate the sum of the first n natural numbers, we repeatedly add each number from n down to 1. We use recursion, which means the function calls itself with a smaller value each time until it reaches a base case, where it stops.
Below are the steps we took:
- First, we create a function called sumNatural() that takes an integer n as input.
- Next, we check if n is equal to 1 . If it is, we return 1 . This is our base case.
- If n is not 1, we return n plus the result of sumNatural(n - 1). This breaks the problem into smaller parts.
- Finally, the function continues to call itself until it reaches the base case, and the results are added one by one as it returns.
C++ Program to Find Sum of Natural Numbers using Recursion
Here's a complete C++ program where we calculate the sum of n natural numbers using recursion.
#include <iostream> using namespace std; // Recursive function to calculate sum of first n natural numbers int sumNatural(int n) { if (n == 1) // base case: when n is 1, return 1 return 1; return n + sumNatural(n - 1); // recursive call } int main() { int n = 9; int sum = sumNatural(n); // print the result cout << "Recursive sum of first " << n << " natural numbers: " << sum << endl; return 0; }
Once you run the above program, you will get the following output, which shows the sum of the first 9 natural numbers calculated using recursion:
Recursive sum of first 9 natural numbers: 45
Time Complexity: O(n) because the function calls itself n times.
Space Complexity: O(n) because each recursive call adds a new frame to the call stack.
Conclusion
In this article, we saw how to find the sum of the first n natural numbers using recursion in C++. We created a function that calls itself by reducing the value of n step by step, until it reaches the base case. This method is simple to understand but uses more memory than a loop because of repeated function calls.