can't figure out the j=j*k expressions
The expression j = j * k
means multiply the value that is currently stored in j
by the value stored in k
and store the result back in j
.
when we say return j does that mean we start at j=1 and go through the
loop and then go to the j=2, go through the loop, j=3 etc?
Not really. return j
is what's known as a return statement. The function named
fact
has a return type of int
and this basically means that it returns an int
value to its caller. For more information, you may watch the short on functions!
Now,there is also another trick here and that is when the body of a for loop is not delimited by curly braces (i.e. {
and }
), the first statement right after the loop is considered the body of that loop and it is the one whose execution repeats as long as the loop continuation condition, in this case the k <= i
, is evaluated to true.
Any subsequent statement is outside of the body of the loop. So the statement return j
is actually executed after the loop ends execution.
where is the j++
The variable j
is used to hold the factorial of the input i
. j++
is capable of increasing the value in j
by one. Why would you ever need to do that?