In your own wordsQuestion 1 · Apply
Loading…
By the end you can write pseudocode for all selection and iteration constructs: IF/ELSE (including nested), CASE, FOR loops (count-controlled), WHILE loops (pre-condition), and REPEAT...UNTIL loops (post-condition). You can justify which loop type fits a problem.
Selection means choosing what to do, based on a condition.
A condition is a question that is either true or false, such as Mark >= 50.
Simple IF runs some statements only when the condition is true:
IF condition THEN
statement(s)
ENDIF
IF...ELSE picks one of two routes. The ELSE part runs when the condition is false:
IF condition THEN
statement(s)
ELSE
statement(s)
ENDIF
Three or more routes need a nested IF: an IF written inside another IF.
Cambridge pseudocode has no separate keyword for a second test. Instead, put a new IF inside the ELSE part, and give that inner IF its own ENDIF:
IF condition1 THEN
statement(s)
ELSE
IF condition2 THEN
statement(s)
ELSE
statement(s)
ENDIF
ENDIF
Count the words: two IFs, so two ENDIFs. Every IF needs its own ENDIF.
Nesting works in the THEN part too:
IF Score >= 50 THEN
IF Score >= 75 THEN
OUTPUT "Distinction"
ELSE
OUTPUT "Pass"
ENDIF
ELSE
OUTPUT "Fail"
ENDIF
Conditions use these comparison operators:
= equal to<> not equal to<, >, <=, >= less than, greater than, less than or equal to, greater than or equal toConditions can also use the logic operators AND, OR and NOT.
Worked example: Nested IF — grade calculator
Input a mark (0-100). Output grade: A (80+), B (70-79), C (60-69), D (50-59), F (below 50).
This grade program has a bug. It gives an F to every mark under 70, because the C and D tests are missing.
65, so it prints F. A mark of 65 should get a C.Keep the test for 70 and the OUTPUT Grade line as they are.
DECLARE Mark : INTEGER
DECLARE Grade : CHAR
OUTPUT "Enter a mark (0-100)"
INPUT Mark
IF Mark >= 80 THEN
Grade ← 'A'
ELSE
IF Mark >= 70 THEN
Grade ← 'B'
ELSE
// write the C, D and F tests here
Grade ← 'F'
ENDIF
ENDIF
OUTPUT Grade
Open this lesson on a computer to edit and run this code and check your answer.
CASE checks one variable against a list of fixed values. It is neater than a long run of nested IFs when every test compares the same variable with a value.
CASE OF Variable
value1 : statement(s)
value2 : statement(s)
OTHERWISE : statement(s)
ENDCASE
OTHERWISE runs when no branch matches. It is optional, but good practice to include.A branch can also cover a range of values with TO. The range includes both ends:
CASE OF Mark
80 TO 100 : Grade ← 'A'
70 TO 79 : Grade ← 'B'
OTHERWISE : Grade ← 'F'
ENDCASE
A mark of 85 matches the first branch, so it gets A. A mark of 75 skips the first branch and matches the second.
Worked example: CASE — menu selection
Input a menu choice (1-4). Output the action: 1 = Add, 2 = Delete, 3 = Search, 4 = Exit. Any other number gives Invalid.