If Statement
One of the perspectives I found useful when learning if statements, is to think of it as:
first check the condition and then branch into different possibilities based on this condition.
Each branch implies a unique sequence of instructions for a given choice of parameters
SomeFunction(parameters)
execute instructions A
if condition X is true
execute instructions Y
else
execute instructions Z
execute instructions B
While Loop
While condition X is true, we remain within the while loop. So we are testing X again, and if true, continue into the while block. When X stops being true, we cease entering the while block and continue with the rest of the function.
while condition X is true
execute instructions Y
execute instructions B
This differs from an IF statement, in that if the statement is true, the block is entered, and then continue on with the function.
What if we need to initialise values?
p ← 1
i ← 1
while (condition X is met)
p ← p · i
i ← i + 1
We are evaluating, then reassinging values to the variables p and i. If we forget to update the values, the loop will be infinite.
For Loop
Updating values happens frequently. So we have a for loop to address this more intuitively, where we are looping through a given collection of variables
for every value of some variable satisfying condition X
execute instructions Y
We ar
AnotherFunction(n)
p ← 1
for every integer i between 1 and n
p ← p·i
return p
W