- Foundation
- About 12 min
- 5 practice questions
Making decisions: if and else
Use selection (if, else, else-if) to choose between actions and trace the result for given inputs.
If something looks wrong, please tell us.
Programs are useful because they can choose. A decision structure tests a condition and picks a path.
Three basic structures
- Sequence: steps run one after another.
- Selection: a condition picks which steps to run (if / else).
- Iteration: steps repeat in a loop.
if, else and else-if
In pseudocode: IF marks >= 40 THEN print Pass ELSE print Fail. The condition is checked; if it is true, the first branch runs; otherwise the else branch runs. An else-if chain tests several conditions in order and stops at the first true one.
Grade rule used below: IF marks >= 80 print A; ELSE IF marks >= 60 print B; ELSE IF marks >= 40 print C; ELSE print Fail.
Worked examples
Example 1. marks = 72. 72 >= 80 is false; 72 >= 60 is true, so it prints B.
Example 2. marks = 40. 40 >= 80 false; 40 >= 60 false; 40 >= 40 true, so it prints C.
Example 3. marks = 39. All conditions are false, so it prints Fail.
Example 4. Even or odd. IF n % 2 == 0 print Even ELSE print Odd. For n = 17, 17 % 2 = 1, so it prints Odd. For n = 20, 20 % 2 = 0, so Even.
Order matters in an else-if chain: the first true condition wins.
Key takeaways
- Selection chooses a path using a condition.
- else-if chains stop at the first true condition.
- n % 2 tests even or odd.
Check your understanding
-
1. Grade rule: IF marks >= 80 print A; ELSE IF marks >= 60 print B; ELSE IF marks >= 40 print C; ELSE print Fail. What prints for marks = 65?
- A
- B
- C
- Fail
Show answer
Answer: B. 65 >= 80 is false; 65 >= 60 is true, so the chain prints B and stops.
-
2. Using the same grade rule, what prints for marks = 80?
- A
- B
- C
- Fail
Show answer
Answer: A. 80 >= 80 is true, so the first branch prints A. The condition includes 80 itself.
-
3. IF n % 2 == 0 print Even ELSE print Odd. What prints for n = 15?
- Even
- Both Even and Odd
- Odd
- Nothing
Show answer
Answer: C. 15 % 2 = 1, which is not 0, so the else branch prints Odd.
-
4. Which basic structure uses a condition to choose which steps to run?
- Sequence
- Iteration
- Constant
- Selection
Show answer
Answer: D. Selection (if / else) picks a path using a condition. Sequence runs steps in order and iteration repeats them.
-
5. How does an else-if chain decide what to run?
- It runs every branch whose condition is true
- It runs only the last true condition
- It tests the conditions in order and runs only the first true one
- It tests the conditions in a random order
Show answer
Answer: C. An else-if chain tests several conditions in order and stops at the first true one, so the order matters.
Sign in to keep track of the lessons you finish.