MODULE 2 • LESSON 07
A program that can only run its statements in sequence does exactly the same thing every time. Real problems need choices: charge a discount only if the bill is large enough, print “Pass” or “Fail”, give a concession fare to children and seniors. The construct that lets an algorithm choose is selection.
In this lesson you will learn to write conditions with relational and logical operators, and to use the three forms of selection the syllabus expects: IF-THEN, IF-THEN-ELSE and nested IF. You will light up the path a value takes through four flowcharts, hunt for the bug in two faulty grading algorithms using a test plan, and write each algorithm in C.
What you will learn
- What selection is and why algorithms need it.
- How to write conditions using relational operators (=, <>, <, <=, >, >=).
- How to combine conditions with AND, OR and NOT, and evaluate them with truth tables.
- The IF-THEN, IF-THEN-ELSE and nested IF structures in pseudocode, flowcharts and C.
- Why the order of tests in a nested IF matters, and how to test the boundaries.
- How a CASE (switch) statement chooses between many options.
Part 1: Conditions
Selection is controlled by a condition (also called a Boolean expression): a question whose answer is either True or False. Conditions are built from relational operators, which compare two values:
| Operator | Meaning | Example | True when… | In C |
| = | equal to | answer = “Y” | answer holds Y | == |
| <> | not equal to | code <> 0 | code is anything but 0 | != |
| < | less than | age < 18 | age is 17 or less | < |
| <= | less than or equal to | qty <= 10 | qty is 10 or less | <= |
| > | greater than | total > 200 | total is more than 200 | > |
| >= | greater than or equal to | mark >= 50 | mark is 50 or more | >= |
Choose between > and >= very carefully. “50 or more passes” is mark >= 50; “more than 50” is mark > 50. The two give different answers only for the boundary value 50, and that is exactly where examiners and testers look.
Combining conditions: AND, OR, NOT
Logical operators join simple conditions into compound ones:
- AND is True only if both parts are True.
age >= 13 AND age <= 18checks a range. - OR is True if at least one part is True.
age < 5 OR age >= 65picks out young children and seniors. - NOT reverses a condition.
NOT (answer = "Y")is the same asanswer <> "Y".
| A | B | A AND B | A OR B | NOT A |
| False | False | False | False | True |
| False | True | False | True | True |
| True | False | False | True | False |
| True | True | True | True | False |
These are the same truth tables you met for logic gates in Module 1. Worked example. With p = 8, q = 4 and r = 3, is (p > q) AND (q > r) True? p > q is True (8 > 4); q > r is True (4 > 3); True AND True is True. If r were 6, q > r would be False, and the whole AND would be False.
In C, AND is written &&, OR is || and NOT is !. Each comparison must be complete: write age >= 13 && age <= 18, not 13 <= age <= 18, which compiles but does something different.
Part 2: IF-THEN
The simplest selection carries out some steps only if a condition is True. If it is False, those steps are skipped and the algorithm carries on after ENDIF.
INPUT total IF total > 200 THEN total ← total - 20 ENDIF OUTPUT total
A shop gives $20 off bills over $200. A bill of $250 becomes $230; a bill of $150 is unchanged. In the flowchart, the Yes path goes through the extra process; the No path goes straight past it, and both meet again before the output.
In C: if (total > 200) { total = total - 20; }. The condition must be in brackets, and the braces mark which statements belong to the IF.
Part 3: IF-THEN-ELSE
When there are two alternatives and exactly one must happen, use IF-THEN-ELSE. The THEN part runs when the condition is True; the ELSE part runs when it is False. One of them always runs, never both.
INPUT mark IF mark >= 50 THEN result ← "Pass" ELSE result ← "Fail" ENDIF OUTPUT result
Use IF-THEN-ELSE rather than two separate IF-THENs (IF mark >= 50 … ENDIF then IF mark < 50 … ENDIF). Two IFs ask the question twice, and if you later change one boundary and forget the other, some marks get both results or neither.
Part 4: Nested IF
A nested IF is an IF statement placed inside the THEN or ELSE part of another IF. It handles more than two outcomes, or a second question that only makes sense after the first has been answered. The most common pattern is a chain of ELSE IFs, used for grade bands, tax brackets and price tiers:
INPUT mark IF mark >= 70 THEN grade ← "A" ELSE IF mark >= 55 THEN grade ← "B" ELSE IF mark >= 40 THEN grade ← "C" ELSE grade ← "D" ENDIF OUTPUT grade
The tests are asked in order from the top, and the first True condition wins; the rest are never asked. That is why the second test can simply say mark >= 55: by the time it is asked, we already know the mark is below 70.
A nest can also put an IF inside the THEN part, when the second question only matters for some cases. For example, children under 3 travel free; otherwise, children under 12 and adults aged 65 or more pay a concession fare:
IF age < 3 THEN
fare ← 0
ELSE
IF age < 12 OR age >= 65 THEN
fare ← 10
ELSE
fare ← 20
ENDIF
ENDIF
Indent each level and close each IF with its own ENDIF so that the reader (and you, when tracing) can see which ELSE belongs to which IF.
Selection in flowcharts
Every selection is a diamond with two labelled exits. For a nested IF, the next diamond sits on one of the exits of the previous one. All paths must join again before the algorithm continues. Use the next activity to see this for yourself.
Try it 1Follow the path
Choose an algorithm, then change the input with the buttons. The path the value takes through the flowchart is outlined in orange (symbols not visited fade), and the pseudocode lines that run are highlighted. Try the boundary values: 200, 50, 70, 55, 40, 5 and 65.
Notice how, in the grade chart, a low mark has to pass through three diamonds before it reaches its box, while a high mark leaves after the first. Also notice that for every input, exactly one grade box is lit: that is the guarantee a well-built nested IF gives you.
Part 5: Order matters, and how to test it
A nested IF can look right and still be wrong. Here are two faulty versions of the grading algorithm:
| Version 2: tests in the wrong order | Version 3: separate IFs, no ELSE |
| IF mark >= 40 THEN grade ← "C" ELSE IF mark >= 55 THEN grade ← "B" ELSE IF mark >= 70 THEN grade ← "A" ELSE grade ← "D" ENDIF | grade ← "D" IF mark >= 70 THEN grade ← "A" ENDIF IF mark >= 55 THEN grade ← "B" ENDIF IF mark >= 40 THEN grade ← "C" ENDIF |
In Version 2, any mark of 40 or more stops at the first test, so nobody ever gets a B or an A. In Version 3, every IF is asked, and a mark of 85 is set to A, then overwritten with B, then with C. Both versions give the right answer for low marks, which is why a careless tester would miss the bugs.
The cure is a test plan that includes a value in every band and the values on each side of every boundary: for the grades, 39 and 40, 54 and 55, 69 and 70, plus extremes such as 0 and 100. Lesson 09 builds full test plans; here is a first taste.
Try it 2Catch the faulty versions
Each button adds a test mark to the table. The Expected column comes from the correct algorithm; the other columns show what Versions 2 and 3 output. Your goal: find a test that exposes each faulty version, using as few tests as you can.
Part 6: Choosing among many options: CASE
When one variable is compared with a list of exact values, a CASE statement (called switch in C) is tidier than a long ELSE IF chain:
INPUT choice CASE choice OF 1: OUTPUT "Adding a record" 2: OUTPUT "Deleting a record" 3: OUTPUT "Goodbye" OTHERWISE: OUTPUT "Invalid choice" ENDCASE
CASE is still selection: exactly one branch runs. It works best for menus and codes. It cannot test ranges such as "mark >= 70" in most languages, so grade bands still need IF.
Part 7: Selection in C
The grading algorithm. In C, the ELSE IF chain is written else if; each branch is in braces; and a single character is stored in a char and printed with %c.
#include <stdio.h>
int main(void)
{
int mark;
char grade;
printf("Mark (0-100): ");
scanf("%d", &mark);
if (mark >= 70) {
grade = 'A';
} else if (mark >= 55) {
grade = 'B';
} else if (mark >= 40) {
grade = 'C';
} else {
grade = 'D';
}
printf("\nGrade: %c\n", grade);
return 0;
}
Sample input: 72
Output:
Mark (0-100): Grade: A
The fare algorithm: an IF-THEN-ELSE nested inside the ELSE of another, with an OR condition written ||.
#include <stdio.h>
int main(void)
{
int age, fare;
printf("Age: ");
scanf("%d", &age);
if (age < 3) {
fare = 0;
} else {
if (age < 12 || age >= 65) {
fare = 10; /* concession */
} else {
fare = 20; /* full fare */
}
}
printf("\nFare: $%d\n", fare);
return 0;
}
Sample input: 70
Output:
Age: Fare: $10
The CASE example as a C switch. Each case ends with break; without it, C would carry on into the next case, which is a common bug. default plays the part of OTHERWISE.
#include <stdio.h>
int main(void)
{
int choice;
printf("1 Add 2 Delete 3 Quit: ");
scanf("%d", &choice);
printf("\n");
switch (choice) {
case 1:
printf("Adding a record\n");
break;
case 2:
printf("Deleting a record\n");
break;
case 3:
printf("Goodbye\n");
break;
default:
printf("Invalid choice\n");
}
return 0;
}
Sample input: 2
Output:
1 Add 2 Delete 3 Quit: Deleting a record
Try it 3Selection practice
Pick a mode. "True or False?" gives values and a compound condition. "Nested IF output" gives a score to run through an award algorithm. Tap New question for another.
Summary
| Idea | Remember |
| Condition | A True/False question built from =, <>, <, <=, >, >= and combined with AND, OR, NOT. |
| IF-THEN | Do something only when the condition is True; otherwise skip it. |
| IF-THEN-ELSE | Exactly one of two alternatives always runs. |
| Nested IF | An IF inside another IF. In an ELSE IF chain the first True condition wins. |
| Testing selection | Test every band and both sides of every boundary. |
| CASE / switch | One variable compared with a list of exact values; exactly one branch runs. |
Review questions
1. Explain the difference between IF-THEN and IF-THEN-ELSE, with an example of each.
Show answer
IF-THEN runs its statements only when the condition is True and does nothing extra when it is False (e.g. IF total > 200 THEN total ← total - 20). IF-THEN-ELSE always runs exactly one of two blocks (e.g. IF mark >= 50 THEN "Pass" ELSE "Fail").
2. What is a nested IF? When is it needed?
Show answer
An IF statement placed inside the THEN or ELSE part of another IF. It is needed when there are more than two outcomes (such as grade bands) or when a second decision only applies after the first has been made.
3. Given a = 15 and b = 22, what does this output? IF a = b THEN OUTPUT "Same" ELSE IF a > b THEN OUTPUT "First" ELSE OUTPUT "Second" ENDIF
Show answer
a = b is False; a > b is False (15 > 22); so the final ELSE runs and the output is Second.
4. Write a correct condition for "x is between 10 and 20 inclusive", and say why brackets help when AND and OR are mixed in one condition.
Show answer
x >= 10 AND x <= 20. Brackets make it clear which parts are combined first, so (a OR b) AND c cannot be misread as a OR (b AND c).
5. Why is it wrong to test mark >= 40 before mark >= 70 in an ELSE IF chain?
Show answer
The first True condition wins. Every mark of 70 or more is also >= 40, so it stops at the first test and is given the lower grade; the A branch can never be reached.
6. List the test marks you would use to test a pass/fail algorithm with a pass mark of 50, and explain why.
Show answer
A clearly failing mark (e.g. 20), the boundary values 49 and 50, and a clearly passing mark (e.g. 85). 49 and 50 check that >= rather than > was used; the others check each branch.
7. Write pseudocode for: input a temperature; output "Cold" below 20, "Warm" from 20 to 30 inclusive, and "Hot" above 30.
Show answer
INPUT temp
IF temp < 20 THEN OUTPUT "Cold"
ELSE IF temp <= 30 THEN OUTPUT "Warm"
ELSE OUTPUT "Hot"
ENDIF
8. In C, what is wrong with if (mark = 50)?
Show answer
It uses = (assignment) instead of == (comparison). It stores 50 in mark and the condition is always True. It should be if (mark == 50).
Homework
- A cinema charges $30, but $20 on Tuesdays, and children under 12 always pay $15. Write pseudocode, draw the flowchart, and write a C program. Decide which test must come first, and justify it.
- Build a test plan (at least 8 rows: input, expected output, reason) for your cinema algorithm.
- Rewrite the grade algorithm as Version 3 (separate IFs) but in ascending order (40, then 55, then 70). Does it work now? Explain why with a trace for a mark of 85.
- Write a
switchprogram for a vending machine: codes 11, 12 and 13 select three drinks; anything else prints "Unknown code". - Evaluate each condition for x = 7, y = 12: (a) x < y AND y < 10 (b) NOT (x > y) OR y = 12 (c) (x + y) MOD 2 = 1.
Mastery quiz: Selection
This 10-question quiz is separate from the short Quick quiz at the end of the lesson. Score 8/10 or higher to earn this lesson’s badge. Your best score is saved in this browser on this device.
Mastery quiz: Selection: IF-THEN, IF-THEN-ELSE and Nested IF
Your course badges: loading saved progress…
View badges
No course badges earned yet. Score 8/10 in a lesson quiz to earn its badge.
Saved in this browser on this device. Clearing browser data may remove your badges.
Answer all 10 questions. Earn this lesson’s badge at 8/10 or higher. Read the explanations, revisit the Try it activities and retry as often as you need. These are self-study badges, not formal grades.
Exam tips
Specimen Unit 1 Paper 01 (2021), Item 28. The output of an IF / ELSE IF / ELSE chain for given values. Test the conditions from the top, stop at the first True one, and check the exact text in that branch.
Specimen Unit 1 Paper 01 (2021), Item 29. A compound AND condition decides which variable changes. Evaluate each comparison separately, combine with the truth table, then apply only the branch that runs.
CAPE 2024 Unit 1 Paper 02, Question 4(c). The output of a nested IF for several inputs. Treat each input as a separate short trace, and remember that statements after ENDIF run whatever the decision. A worked answer is linked in the Go further box.
CAPE 2024 Unit 1 Paper 02, Question 3(b)(ii); CAPE 2012 Unit 1 Paper 02, Question 3(c). Writing selection for several bands or categories. Put the tests in an order where the first True condition is always the right one, include a final ELSE for "anything else", and say what happens at each boundary.
More worked answers are on the CS Solutions page.
Previous: Module 2 • Lesson 06 – Sequence, Input, Output and Assignment. Next: Module 2 • Lesson 08 – Loops: Bounded and Unbounded Iteration.
Syllabus link: CAPE Computer Science (CXC A19/U2/21), Problem-Solving with Computers (Unit 1, Module 2). Specific Objective 6: explain constructs used in structured programming (the control structure selection: IF-THEN, IF-THEN-ELSE and nested selection, with relational and logical operators).
Video search terms
Search YouTube for: "nested if else pseudocode", "if else if ladder in C", "AND OR NOT truth table conditions", "switch case break C".
Try it 4Quick quiz
Tap an answer. All eight questions are self-checks on this lesson.
Updates
2026/12/01
- Updated the copyright line.
- Published. Previous/Next links and the mastery quiz links now use the full lesson addresses.
- Small script tidy-up for the site (no change to how the activities work).
2026/11/24
- Linked Previous/Next and the mastery quiz URLs to draft shortlinks (?p=ID), which will redirect to the permalink after publish.
- First version of the lesson.
© 2026 islandclass.org
