C++

A C++ Program That Uses Recursion To Calculate The Sum Of N Natural Integers

Natural numbers are defined as 1, 2, 3,…, n. This software outputs the sum of the first n natural integers given the value of n (input by the user).
For instance: This application would show the sum of the first six natural integers if the user entered n as 6:
1+2+3+4+5+6 = 21

Recursion is used in this program to find the sum, although loops can also be used to address this issue: Using a loop, a C++ program can calculate the sum of n natural integers.

Example: A recursive program to compute and display the sum of n natural integers

You should be familiar with C++ functions, if-else statements, and recursion in order to comprehend this program.

The reasoning behind this program is as follows:
sum(5) = 5 + sum(4) = 5 + 4 + sum(3) = 5 + 4 +, sum(2) = 5 + 4 + 3 + 1, and sum(0) = 15
Therefore, the recursive function should seem as follows: 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

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button