DEV Community

Discussion on: Solution: Number of Steps to Reduce a Number to Zero

Collapse
 
nithish_13 profile image
Nithish Kumar

Hey hi, I cant understand what is happening on this line.
// for (; num; ans++)
Could u explain?

Collapse
 
seanpgallivan profile image
seanpgallivan

Sure!

The for loop declaration is broken up into three parts. The first part is an expression that's executed once at the very beginning of the loop. Usually it's used to initialize loop variables. Here, I'm using ans as the iterable, but I also want to be able to refer to it once the loop is over, so I have to initialize it outside the loop. Since I don't have any other loop variables to initialize, the first part is left blank.

The middle portion is the "while" conditional. Here, I want to continue looping while num > 0. Since 0 evaluates as falsy and any other number evaluates as truthy, I can simplify that conditional to just num, so that when num decrements to 0, it triggers an end to the loop.

The third part is more standard: it's an expression that will run at the end of each loop, before restarting the next iteration. In this case, it's a fairly standard variable increment.

Collapse
 
nithish_13 profile image
Nithish Kumar

Thanks a ton 😄