1.

Write a program to print the factorial of a given input number.

Answer»

Example:

Input:

5

OUTPUT:

120

In practically all interviews, factorial is one of the most frequently asked questions (INCLUDING developer interviews) Developer interviews place a greater emphasis on programming concepts such as dynamic programming, recursion, and so on, whereas Software Development Engineer in TEST interviews place a greater emphasis on handling edge scenarios such as max values, min values, negative values, and so on, and approach/efficiency becomes secondary.

The following recursive formula can be used to calculate factorial.

n! = n * (n-1)!n! = 1 if n = 0 or n = 1

Code:

#include &LT;bits/stdc++.h>using namespace std;// function to find the factorial of given numberint findFactorial(unsigned int n){ if (n == 0) return 1; return n * factorial(n - 1);}int main(){ int number = 5; if(number < 0) { cout << "Negative numbers do not have factorial" << "\n"; return 0; } cout << "Factorial of " << number << " is " << findFactorial(number) << “\n”; return 0;}

Output:

Factorial of 5 is 120

Explanation:
In the above code, the function findFactorial finds the factorial of a given input number. Before making the function call, we check if the given number is negative. Negative numbers do not have a factorial and so we must display appropriate messages for it. 



Discussion

No Comment Found