We looked at the basic programming constructs of sequence, selection, and iteration in 1.02 (Pseudocode) and 1.03 (Flowcharts). We will go into more detail here.
Example 1 shows a basic IF statement.
Example 1
passcode ← USERINPUT
IF passcode = 1234 THEN
OUTPUT "OK"
ELSE
OUTPUT "Wrong password"
ENDIF
A nested IF statement means an IF statement inside another IF statement.
Example 2 shows a nested IF statement.
Example 2
user ← USERINPUT
passcode ← USERINPUT
IF passcode = 1234 THEN
IF user = "admin" THEN
OUTPUT "Full access"
ELSE
OUTPUT "Restricted access"
ENDIF
ELSE
OUTPUT "Wrong password"
ENDIF
ELSE IF statements can be used to chain together multiple conditions.
Example 3 shows an IF statement with multiple ELSE IF statements.
Example 3
option ← USERINPUT
IF option = 1 THEN
option_1()
ELSE IF option = 2 THEN
option_2()
ELSE IF option = 3 THEN
option_3()
ELSE IF option = 4 THEN
option_4()
ELSE
OUTPUT "Invalid"
ENDIF
ELSE IF statements can often be simplified by using CASE statements.
Example 4 shows an algorithm which performs exactly the same task as the one in Example 3.
Example 3
option ← USERINPUT
CASE option OF
1: option_1()
2: option_2()
3: option_3()
4: option_4()
DEFAULT: OUTPUT "Invalid"
ENDCASE
How does including a
DEFAULT case in a CASE statement make the code more robust?
It's a good idea to make sure the program knows what to do if it receives an unexpected input. Otherwise, it might crash.