Sum of the "N" natural numbers using recursion and iterative method in CPP language


So in this post, I am gonna show you how we can find the total sum of the given "N" natural number in the CPP program using recursive as well as iterative approach so let's begin.




1. using an iterative approach:

In this approach, we will take 3 integers variables as below in the code first "n" for reaching the range of the last value and parallelly we will increment "i" with 1 add the sum in the "sum" variable and finally when the loop will break the condition we will get the final result. 

Explanation:

i = 0 , sum = 0  
i = 1 , sum = 1  
i = 2 , sum = 3  
i = 3 , sum = 6  
break

Code





2. Using recursive approach:

For example, in the below image the first n-1 elements sum + sum of the last element is equal to the sum of all elements, so sum(0) = 0 and sum of n > 0 = sum(n-1) + n using this approach sum function will call itself until it reaches to the last point at sum(0) base condition on which the recursion will stop and return back then it will return than the value "0" and after return back the value and add both values sum(n-1) + n.



    
    Recursion Tree

    Code : 

 

So this is how we can find the sum of N natural numbers using recursion and iterative method in the CPP language.I have used input.txt and output.txt file for i/p you can create these files in your local project directory or you can download this code by clicking the link below:-

Download Code

Comments

Popular posts from this blog

Factorial of the "N" natural numbers using recursion and iterative method in CPP language

Build a weather web application in React JS | React JS beginner Tutorial

How to connect adb devices in linux | Run apps on a hardware device android