Selection: IF
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
IF makes a decision
- Selection chooses what to do, based on a test.
IFruns itsTHENblock only when the test isTRUE.- The block ends at
ENDIF.
IF Age >= 18 THEN
OUTPUT "You may vote"
ENDIF
IF ... ELSE
ELSEgives the path to take when the test isFALSE.- Exactly one of the two blocks runs.
IF Mark >= 50 THEN
OUTPUT "Pass"
ELSE
OUTPUT "Fail"
ENDIF
Explore
TRUE or FALSE — which block runs?
IF runs its THEN block when the test is TRUE; ELSE covers every other case.
Comparison operators
=equal to,<>not equal to.<><=>=compare sizes.
IF N MOD 2 = 0 THEN
OUTPUT "even"
ELSE
OUTPUT "odd"
ENDIF
Watch out
- In a test,
=means "is equal to". (The arrow←is for storing a value.) - Don't forget
THENafter the test andENDIFto close the block.
Common mistakes
- Write
IF ... THEN ... ELSE ... ENDIF— do not forgetENDIF. - Compare with
=in pseudocode conditions.
Now you try
- Read the input, then choose with
IF ... ELSE ... ENDIF. - Press Check answer to test it.
Read an INTEGER N. If it is greater than 0, output positive, otherwise output not positive. For input 5, output positive.
Click Run to see the output here.
Read a Mark. Output Pass if it is 50 or more, otherwise Fail. For input 40, output Fail.
Click Run to see the output here.
Read an INTEGER N. Output even if N MOD 2 = 0, otherwise odd. For input 8, output even.
Click Run to see the output here.