Problem Statement
given a number, write a JavaScript program with a function that takes a number as argument, find the factorial of the number using recursion function, and returns the result
Solution
create a function findFactorial()
that takes n
as argument
if n
is 0
or 1
, the function returns 1
, else the function returns n * findFactorial(n - 1)
. the function calls itself, findFactorial()
, hence a recursive function
Program
1. factorial of a number using recursion function
function findFactorial(n) {
if (n == 0 || n == 1) {
return 1;
}
return n * findFactorial(n - 1);
}
var n = 5;
console.log(n+'! = '+ findFactorial(n));