0 votes
in Programming by (1.9k points)
function FirstFactorial(num) { 
      for(var i = num - 1; i > 0; i--) {
           return num * i; 
      }        
    };

  console.log(FirstFactorial(8))

I just want to know what writing my code like this doesn't print the factorial? Instead I only get 56, which is 8 * 7. I thought that if i use the for loop that it would keep going?

1 Answer

0 votes
by (2k points)

Using:

for(var i = num - 1; i > 0; i--) {
    return num * i; 
}

It will return num*(num-1) value. Since it will return the value in the first iteration.

Instead use:

Using recursion:

function FirstFactorial(num) {
    if(num==1)
        return num;
    else
        return num*(FirstFactorial(num-1))
}

or:

fact=num;
for(var i = num - 1; i > 0; i--) {
    fact*=i; 
}
return fact;

 

 

131 questions

117 answers

7 comments

378 users

Welcome to Todayask Q&A, where you can ask questions and receive answers from other members of the community.
...