Posts

Showing posts with the label Data Structure

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

Image
In this post, I am gonna show you how to find factorial of N numbers using recursion and as well as iterative approach, Here is the video clip of recursion that will visualize that how the recursion work.    Here's the code below in this code I have used input.txt and outout.txt for input-output purpose. and you can also use the code below and visualize using the recursion visualizer tool using this link https://recursion.now.sh/ Recursive approach It will take one integer value to find out the factorial and in this, we will take the first base condition, where the recursion will stop and we will get our final answer, and second which will create the stack size of the given number. Iterative Approach For the iterating approach, we just have to iterate the one variable "i" until we got the last number "n". and parallelly multiplying it with the "fact" variable which we have declared as "1" before.

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

Image
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 retur...