The numbers 1, 2, 3,…, n are known as natural numbers. This program takes the value of n (entered by user) and prints the sum of first n natural numbers.
For example: If user enters the value of n as 6 then this program would display the sum of first 6 natural numbers:
1+2+3+4+5+6 = 21
In this program we are using recursion to find the sum, we can also solve this problem using loops: C++ program to find the sum of n natural numbers using loop.
Example: Program to calculate and display the sum of n natural numbers using recursion
To understand this program, you should have the knowledge of C++ recursion, if-else statement and functions.
The logic we are using in this program is:
sum(5) = 5+sum(4) = 5+4+sum(3)=5+4+3+sum(2) = 5+4+3+2+sum(1) = 5+4+3+2+1+sum(0) = 15
So the recursive function should look like this: sum(n) = n+sum(n-1)
#include<iostream> using namespace std; /* This is function declaration, When you define function * after the main then you need to declare it like this. * If you define the function before main then no need to * declare function. */ int sum(int n); int main(){ int n; cout<<"Enter the value of n(should be positive integer): "; cin>>n; /* Here we are checking whether the entered value of n is * natural number or not. If user enters the zero or negative * value then display error message else prints the sum of n * natural numbers. */ if(n<=0){ cout<<"The entered value of n is invalid"; } else{ cout<<"Sum of n natural numbers is: "<<sum(n); } return 0; } int sum(int n){ /* We are calling sum function recursively until the value * of n is equal to 0. */ if(n!= 0) { return n + sum(n-1); } return 0; }
Output:
Enter the value of n(should be positive integer): 5 Sum of n natural numbers is: 15
Leave a Reply