Factorial Using Recursion in c++ | Recursion in C++

Finding Factorial

What is Factorial?

The product of an integer and all the integers below it; e.g. factorial four ( 4! ) is equal to 24.
and it works something like this; 4*3*2*1=24

Logic for simple factorial:

The logic is very simple you just have to multiply the given number is this sequence;e.g give number is n
so we will multiply it like this n*n-1*n-2*n-3…….
till the number below n is not zero. And factorial will be found.

Recursion in programming:

When a function call itself with respect to some condition this is called recursion. Every function that implements recursion, has a base condition. This is very basic concept in programming, it saves execution time and provide efficiency. It is just like loops because a function call itself multiple times. The code works in an iterative manner to perform a specific task. And when the task is completed the Functions stops and gives us the desired output or answer.

C++ example:

You can use any language you want,but i’ll use c++ as it is the most common language.
Logic remains the same no matter which language you use.

Code:

/*

*@author: Abdul Aziz

*@ProgramName: Finding factorial of a number using recursion method

*@SoftwareUsed: Developer C++ (Dev)

this is a multi-line comment. You can remove all comments if you want.

*/

//Header Files

#include <iostream>
#include <string>

using namespace std;

//Declaring and defining a function

long fact(int n){
int result=1;
if (n>0){ //base condition
result=n*fact(n-1); //this is the main formula that i am using to find factorial of a number
} else{
return result; // This is returning the result of the whole function
}

}
int main () {

cout << “Factorial is: “<<fact(4); //calling of function by giving input (You can give any input you want)

return 0;
}

If you want to get more posts about programming than goto this link .And If you guys have any questions regarding any concept don’t hesitate to comment it free.😊

Thank you!

2 Comments

Add a Comment

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