- Practice
- About 14 min
- 5 practice questions
Control structures: decisions and loops
Trace if-else statements and loops to find their output, including nested conditions.
If something looks wrong, please tell us.
Programs use three basic structures: sequence (steps in order), selection (choose a path with a condition) and iteration (repeat steps in a loop). Almost every output-tracing question is built from these.
Selection and iteration
- if-else runs one block when the condition is true, another when false.
- A for loop repeats a set number of times.
- A while loop repeats while the condition is true; if it never becomes false, you get an infinite loop.
- The loop condition is checked before each repetition.
Worked examples
Example 1. Trace: X = 10; if X > 5 then print "High" else print "Low". Since 10 > 5 is true, the output is High.
Example 2. Trace: S = 0; for I from 1 to 5 step 2, S = S + I; print S. The loop runs for I = 1, 3, 5. S becomes 1, then 4, then 9. Output: 9.
Example 3. Factorial: F = 1; for N from 1 to 5, F = F x N. F goes 1, 2, 6, 24, 120. Output: 120.
Trace with a table: write each variable after every step. A loop with a condition that never turns false never ends.
Key takeaways: trace loops with a value table and count repetitions carefully, including the starting and ending values.
Check your understanding
-
1. Trace: K = 2; while K < 5, K = K + 1; print K. What is printed?
- 5
- 4
- 2
- 6
Show answer
Answer: A. K goes 3, 4, 5. When K is 5, the condition 5 < 5 is false, so the loop stops and 5 is printed.
-
2. Trace: S = 0; for I from 1 to 7 step 2, S = S + I; print S. What is printed?
- 28
- 9
- 7
- 16
Show answer
Answer: D. I takes 1, 3, 5, 7. S becomes 1, 4, 9, 16. Output: 16.
-
3. Trace: X = 3; if X > 5 then print "High" else print "Low". What is printed?
- High
- Both High and Low
- Nothing
- Low
Show answer
Answer: D. 3 > 5 is false, so the else branch prints Low.
-
4. How many times does a loop run for I from 2 to 10 step 2?
- 4
- 5
- 9
- 10
Show answer
Answer: B. I takes 2, 4, 6, 8 and 10, which is 5 values. Count both ends.
-
5. The three basic structures of a program are
- Sequence, selection and iteration
- Input, output and storage
- Compiler, interpreter and assembler
- Class, object and method
Show answer
Answer: A. Programs are built from sequence (steps in order), selection (a condition picks a path) and iteration (repeating steps).
Sign in to keep track of the lessons you finish.