Factorialize a Number Using a For Loop

Tell us what’s happening:
Ok so I actually got the correct answer using recursion, but I went back to look at the solution using a for loop and was totally thrown off. I don’t understand why the exit condition for the loop is “num >= 1”. Seems to me that the exit condition should be num <= 1, or num <= 0, since that is when we want the loop to stop, correct? When num counts down from 5 down to 1 and stops. That’s how my mind is thinking of it anyway, but that answer doesn’t work. Can someone please explain why so I can comprehend?

Thanks!

Nick

Your code so far

function factorialize(num) {
  for (i = 1; num >= 1; num--) {
    i = num * i;
  }
  return i;
}

factorialize(5);

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36.

Link to the challenge:

num >= 1 is not the exit condition. It’s the looping condition. The loop will continue as long as num >= 1. You’re right about the exit condition though, since you can argue that the exit condition is the opposite of the looping condition, which is num < 1 (or num <= 0).

1 Like

That makes so much sense! Bing! Lightbulb.

So how do you know when you’re using a looping condition or an exit condition? I thought while loops used looping conditions and for loops used exit conditions. Or can a for loop use either one?

Both always use looping conditions.

1 Like