What is the Factorial of a number:

Factorial is the product of all the positive integers between 1 and a given positive integer. The given positive integer itself would also be included in the product. Factorial is represented as n! where n is a given positive integer. Here is an example of how we can find a factorial of a positive integer.

5! = 5 x 4 x 3 x 2 x 1 = 120

6! = 6 x 5 x 4 x 3 x 2 x 1 = 720

Logic building of factorial of a given positive number in C++ :

Before building the logic of factorial it is very important to keep a few things in mind:

1- A factorial of negative numbers doesn’t exist.

2- A factorial of 0 is always 1.

So the first thing we will check while writing the factorial code for a given number is that the entered number should be a positive integer, if the integer is 0, then we simply return 1 because as mentioned above that the factorial of 0 is always 1. and if the entered integer is a positive integer greater then 0 we will keep on multiplying all the number greater then and equal to 1 and less then and equal to the given number.

Below is the code and code explanation for factorial in iterative and recursive approaches:

Iterative Approach:

#include<iostream>
using namespace std;

int fact(int num){                // Defining a function called fact with a single parameter num
    int result = 1;
    if(num < 0 || num == 0){      // Checking if the number is equal to 0 or less then 0
        return 1;                 // In both the conditions this if statement will return 1
    }
    else{
    for(int i = 1; i <= num; i++){   // A for loop starting from 1 upto the given positive integer
        result = result * i;         // The numbers are getting multiplied and get store in the variable result
        }
    }
    return result;                  // Returning the result
}


int main(){

    cout<<fact(6);               // Calling the function with a positive integer 6, and the result will be 720

    return 0;
}

Recursive Approach:

#include<iostream>
using namespace std;

int fact(int num){     // Defining a function called fact with a single parameter num
    if(num == 0 || num < 0){    // Checking if the number is equal to 0 or less then 0
        return 1;              // In both the conditions this if statement will return 1
    }
    else{
        return num * fact(num - 1); // recursively calling the function fact(int num), till it gets the factorial
    }
}
int main(){

    cout<<"Enter a positive integer you want to to find the factorial of: "<<endl; // Asking user to enter an integer
    int number;   // Defining a variable called number to store the user enterd integer
    cin>>number;     // Storing the integer in the variable called number
    cout<<fact(number)<<endl;  // Calling the function fact(number)

    return 0;
}

Leave a Reply

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