MODULE 3 • LESSON 05
In Module 2 you designed algorithms that make decisions: IF a mark is at least 50 THEN output “Pass” ELSE output “Fail”, and CASE statements that choose one of several actions. Now you will write those decisions in C. C gives you two selection statements: if (with else and else if) for any condition, and switch for choosing among fixed values. Both depend on conditions, so we start with how C works out whether something is true.
Selection is where many subtle bugs live: a single = where == was meant, a missing break, an else that pairs with the wrong if, a semicolon in the wrong place. This lesson shows each of these traps so that you can spot them in your own code and in exam questions.
What you will learn
- How C represents true and false, and how to write conditions with relational and logical operators.
- How to write if, if-else and else-if ladders, and why the order of tests matters.
- How nested if statements work, and the dangling else rule.
- Why = and == are different, and other common selection bugs.
- How to write a switch statement with case, break and default, including fall-through and grouped cases.
- How to choose between if and switch, and how to translate pseudocode IF and CASE into C.
Part 1: Conditions in C
C has no separate Boolean type in the syllabus programs. Instead it uses integers: 0 means false and any non-zero value means true. When C evaluates a comparison, the result is the int 1 if it is true and 0 if it is false. So printf("%d", 7 > 3); prints 1.
| Operator | Meaning | Example | Value when x = 5 |
| == | equal to | x == 5 | 1 |
| != | not equal to | x != 5 | 0 |
| < | less than | x < 3 | 0 |
| > | greater than | x > 3 | 1 |
| <= | less than or equal to | x <= 5 | 1 |
| >= | greater than or equal to | x >= 9 | 0 |
Conditions are combined with the three logical operators. Their truth tables are the same as the AND, OR and NOT gates from Module 1:
| Operator | Name | True when | Example |
| && | AND | both sides are true | mark >= 0 && mark <= 100 |
| || | OR | at least one side is true | ans == ‘Y’ || ans == ‘y’ |
| ! | NOT | the condition is false | !(age >= 18) |
Points to remember:
- Range checks need two comparisons joined by &&. In maths you write 0 ≤ mark ≤ 100, but in C
0 <= mark <= 100is always true (it compares 0 <= mark first, giving 0 or 1, and both are ≤ 100). Writemark >= 0 && mark <= 100. - Precedence: ! is applied first, then arithmetic, then relational operators (< > <= >=), then == and !=, then &&, then ||. Brackets make your intention clear and cost nothing.
- Short-circuit evaluation: C stops as soon as the answer is known. In
count != 0 && total / count > 50the division never happens when count is 0, which prevents a division-by-zero error. - Characters are compared by their codes, in single quotes:
grade == 'A'. - Real numbers are stored approximately (Module 1), so avoid testing them with ==. Test a range instead, for example
fabs(x - 0.3) < 0.0001.
Part 2: if and if-else
The simplest selection runs a statement only when a condition is true:
if (mark >= 50) {
printf("Pass\n");
}
The condition must be in brackets. The statements to run are placed in a block in braces. To do one thing when the condition is true and another when it is false, add else:
if (mark >= 50) {
printf("Pass\n");
} else {
printf("Fail\n");
}
If a branch has only one statement the braces may legally be left out, but this course always uses them: they prevent the bugs shown later in this lesson and make adding a second statement safe. Indent the statements inside each block (Module 3 also assesses good style), but remember that the compiler ignores indentation completely. Only the braces decide what belongs to what.
The stray semicolon. if (mark >= 50); with a semicolon after the bracket is legal C: the semicolon is an empty statement that becomes the whole body of the if. The block underneath then runs every time, whatever the mark. gcc with -Wall warns about this; never put a semicolon directly after the condition.
Part 3: The else-if ladder
When there are more than two outcomes, chain the tests with else if. C tests each condition from the top and runs the block for the first one that is true; all the remaining tests are skipped. The final else (optional) catches everything that did not match. This is the C version of the nested IF or multi-way selection from Module 2.
Worked example 1: a grade ladder with validation
The user typed 74. The first if checks scanf’s return value (Lesson 04) to reject non-numeric input, then the ladder checks the range before awarding a grade.
#include <stdio.h>
int main(void)
{
int mark = 0;
printf("Enter mark: ");
if (scanf("%d", &mark) != 1) {
printf("That is not a number.\n");
return 1;
}
if (mark < 0 || mark > 100) {
printf("Invalid mark\n");
} else if (mark >= 80) {
printf("Grade: A\n");
} else if (mark >= 65) {
printf("Grade: B\n");
} else if (mark >= 50) {
printf("Grade: C\n");
} else {
printf("Grade: F\n");
}
return 0;
}
Sample input: 74
Output:
Enter mark: Grade: B
Notice the order of the tests. Because the ladder stops at the first true condition, the conditions go from the highest band down, and each one only needs a lower bound: by the time C reaches mark >= 65, it already knows the mark is below 80. If you put mark >= 50 first, every mark of 50 or more would get a C and the A and B branches could never run. The drill below includes ladders in the wrong order so you can see the effect.
Notice also return 1; inside the first if. Returning from main ends the program at once, and a non-zero value tells the operating system that something went wrong.
Part 4: Nested if and the dangling else
An if statement can be placed inside another. This suits decisions that depend on an earlier decision, such as a shop that treats members and non-members differently and then looks at the order total.
Worked example 2: shipping charges
Members pay $15 shipping, or nothing on orders of $200 or more. Non-members pay $40, or nothing on orders of $500 or more. The user entered 250 and y.
#include <stdio.h>
int main(void)
{
double total = 0.0, ship = 0.0;
char member = 'N';
printf("Order total: ");
scanf("%lf", &total);
printf("Member (Y/N): ");
scanf(" %c", &member);
if (member == 'Y' || member == 'y') {
if (total >= 200.0) {
ship = 0.0;
} else {
ship = 15.0;
}
} else {
if (total >= 500.0) {
ship = 0.0;
} else {
ship = 40.0;
}
}
printf("\nShipping: $%.2f\n", ship);
printf("To pay: $%.2f\n",
total + ship);
return 0;
}
Sample input: 250 y
Output:
Order total: Member (Y/N): Shipping: $0.00 To pay: $250.00
The OR test accepts upper or lower case, and ” %c” skips the newline left after the number (Lesson 04). Each inner if-else is completely inside one branch of the outer if-else, and the braces make that unmistakable.
The dangling else. Without braces, which if does an else belong to? C’s rule is: an else pairs with the nearest preceding if that does not already have an else, regardless of indentation. Try it 1 includes a program whose indentation suggests one thing while C does another. Braces remove the problem completely.
= is not ==. if (code = 7) does not compare. It assigns 7 to code, and the value of the assignment (7) is non-zero, so the condition is always true and code has been changed. The compiler accepts it because assignment inside a condition is legal; gcc with -Wall warns “suggest parentheses around assignment used as truth value”. Some programmers write the constant first, if (7 == code), so that a missing = becomes a compile error.
Try it 1Selection runner
Pick a program and input values, then predict the output. The runner shows which lines ran (green) and why. Two of these programs contain a classic bug.
The dangling else fix is to add braces round the inner if, so the else is forced to pair with the outer one:
if (age >= 18) {
if (member == 1) {
printf("Member rate");
}
} else {
printf("Too young");
}
Part 5: The switch statement
When a decision depends on one variable matching one of several exact values, such as a menu choice, a size code or an enum value, a switch statement is clearer than a long ladder of == tests. It is C’s version of the CASE statement in pseudocode.
switch (choice) {
case 1:
printf("Tea");
break;
case 2:
printf("Coffee");
break;
default:
printf("Water");
}
The rules:
- The expression in brackets must have an integer type: int, char or an enum. It cannot be a float, double or string.
- Each case label must be a constant (such as 2, 'Y' or MEDIUM), and no two labels may be equal. Ranges such as "case 50 to 64" are not allowed; use an if ladder for ranges.
- C jumps to the matching case and runs statements from there until it meets break (or the closing brace). break leaves the switch.
- If you leave out break, execution falls through into the next case’s statements. This is usually a bug, but it is also how you give several values the same action: stack the labels, as in
case 'c': case 'C':. - default runs when no case matches. It is optional, but good practice: it handles invalid input.
Worked example 3: a menu using enum and char
The first switch uses the enum constants from Lesson 03 as case labels (SMALL is set to 1 so the numbers match the menu). The second switches on a char and groups upper and lower case letters. The user chose size 2 and topping P.
#include <stdio.h>
enum Size { SMALL = 1, MEDIUM, LARGE };
int main(void)
{
int size = 0;
char top = ' ';
double price = 0.0;
printf("Size 1-3: ");
scanf("%d", &size);
switch (size) {
case SMALL:
price = 25.00;
break;
case MEDIUM:
price = 35.00;
break;
case LARGE:
price = 45.00;
break;
default:
printf("\nNo such size.\n");
return 1;
}
printf("Topping (c/p/n): ");
scanf(" %c", &top);
switch (top) {
case 'c':
case 'C':
price += 5.00;
break;
case 'p':
case 'P':
price += 7.50;
break;
default:
break;
}
printf("\nTotal: $%.2f\n", price);
return 0;
}
Sample input: 2 P
Output:
Size 1-3: Topping (c/p/n): Total: $42.50
Notice how readable case MEDIUM: is compared with case 2:, and how default in the first switch rejects an invalid size and ends the program.
Try it 2switch fall-through lab
Choose a value for choice and switch each break on or off (tap the buttons or the break lines in the code). Green lines run. Match all five target outputs.
Part 6: Choosing between if and switch
| if / else if | switch | |
| Tests | any condition: ranges, several variables, real numbers | one integer, char or enum expression against exact constant values |
| Best for | grade bands, validation, combined conditions | menus, codes, enum values, single letters |
| Pitfalls | = for ==, wrong test order, dangling else, stray semicolon | missing break, non-constant case labels, no default |
| Pseudocode | IF ... THEN ... ELSE ... ENDIF | CASE ... OF ... OTHERWISE ... ENDCASE |
Any switch can be rewritten as an else-if ladder of == tests, but not every ladder can become a switch. When translating pseudocode in an exam, a CASE with exact values maps naturally to switch, with OTHERWISE becoming default and a break after each case. A CASE with ranges must become an else-if ladder.
Worked example 4: from pseudocode to C
A Module 2 algorithm for a taxi fare reads the distance in km and a code letter for the time of day. Here is part of the pseudocode, followed by the C.
IF distance <= 0 THEN
OUTPUT "Invalid distance"
ELSE
CASE code OF
"D": rate <- 6.00
"N": rate <- 9.00
OTHERWISE: rate <- 0
ENDCASE
ENDIF
if (distance <= 0) {
printf("Invalid distance\n");
} else {
switch (code) {
case 'D':
rate = 6.00;
break;
case 'N':
rate = 9.00;
break;
default:
rate = 0;
}
}
Each structure keeps its shape: IF-ELSE-ENDIF becomes if-else with braces, CASE becomes switch with a break after every case, OTHERWISE becomes default, and the arrow for assignment becomes =. The single characters "D" and "N" become char constants in single quotes, because code is a char. Notice that the switch sits completely inside the else block: selection statements can be nested inside each other in any combination.
Try it 3Condition and ladder practice
Pick a mode. "Condition value" asks whether C gives 1 or 0. "Ladder" asks which grade a ladder produces; watch out for ladders tested in the wrong order.
Summary
| Idea | Remember |
| Truth values | 0 is false, non-zero is true; comparisons give 1 or 0. |
| Operators | == != < > <= >=, combined with && || ! |
| Ladder | First true condition wins; order the tests carefully. |
| Nesting | An else pairs with the nearest unmatched if; use braces. |
| Traps | = instead of ==, stray semicolon, 0 <= x <= 100. |
| switch | Integer, char or enum; constant cases; break; default; fall-through. |
Review questions
1. What value does C give to the expression 8 <= 3? And to 8 != 3?
Show answer
0 (false) and 1 (true).
2. Write a condition that is true when temp is between 20 and 30 inclusive.
Show answer
temp >= 20 && temp <= 30
3. Explain why if (x = 0) never runs its body, whatever x was.
Show answer
It assigns 0 to x; the value of the assignment is 0, which is false. It should be if (x == 0).
4. Write an if-else statement that prints "Even" or "Odd" for an int n.
Show answer
if (n % 2 == 0) {
printf("Even\n");
} else {
printf("Odd\n");
}
5. A ladder starts with if (age >= 13) printf("Teen"); else if (age >= 18) printf("Adult"); Explain the bug and fix it.
Show answer
Every age of 18 or more is also at least 13, so "Adult" can never print. Test age >= 18 first, then age >= 13.
6. State the rule C uses to pair an else with an if.
Show answer
An else belongs to the nearest preceding if (in the same block) that does not already have an else.
7. Give TWO restrictions on the expression and labels of a switch statement.
Show answer
The expression must be an integer type (int, char or enum), not float, double or a string; case labels must be constants, and each label must be different. (Ranges are not allowed.)
8. What happens if break is left out of a case? Give one situation where this is useful.
Show answer
Execution falls through into the following case’s statements. It is useful when several values share one action, such as case 'y': case 'Y':.
9. Rewrite as a switch: if (d == 1) printf("Mon"); else if (d == 2) printf("Tue"); else printf("Other");
Show answer
switch (d) {
case 1: printf("Mon"); break;
case 2: printf("Tue"); break;
default: printf("Other");
}
Homework
- Write a program that reads three integers and prints the largest. Test it with a plan that includes equal values (Module 2 Lesson 09).
- Write a program that reads a year and prints whether it is a leap year: divisible by 4, except century years, which must be divisible by 400.
- Write a calculator that reads two numbers and an operator character (+, -, *, /) and uses a switch to print the result. Use default for an unknown operator, and an if inside the / case to prevent division by zero.
- Write an enum for the traffic light colours and a switch that prints the action for each colour.
- Take the "Dangling else" program from Try it 1, type it in with -Wall, and record the warning gcc gives. Then fix it with braces.
Mastery quiz: Selection in C
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 in C: if, else if and switch
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
CAPE 2024 Unit 1 Paper 02, Question 4(c). Tracing nested IF statements to find the output. Work through one condition at a time, write down whether each is true or false, and remember that only one branch of each if-else runs.
CAPE 2024 Unit 1 Paper 02, Question 3(b). Selecting a value (such as a rate) from bands. Make sure every band is covered exactly once, including the boundary values, and order an else-if ladder correctly.
CAPE 2019 Unit 1 Paper 02, Question 5, Part B. A C program that validates input with a compound condition. Check whether the question needs AND or OR, and test boundary values in your head before you finish.
CAPE 2012 Unit 1 Paper 02, Question 3(c). Writing selection logic from a description. When you translate pseudocode, keep the same structure, use == for comparison, and add braces to every branch.
More worked answers are on the CS Solutions page.
Previous: Module 3 • Lesson 04 – Input and Output in C: scanf, printf and Formatted Reports. Next: Module 3 • Lesson 06 – Loops in C: for, while and do-while.
Syllabus link: CAPE Computer Science (CXC A19/U2/21), Programming (Unit 1, Module 3). Specific Objective 5 (first part): use conditional and iterative control constructs (conditional: if, case statements). Loops (for, while) follow in Lesson 06.
Video search terms
Search YouTube for: "C if else if ladder", "C switch case break fall through", "C dangling else".
Try it 4Quick quiz
Tap an answer. All eight questions are self-checks on this lesson.
Updates
2026/12/01
- Updated the copyright line.
2026/11/24
- First version of the lesson.
© 2026 islandclass.org
