Understand and use nested selection and iteration statements
Programming Concepts: Nested Selection & Iteration Statements
What is a Selection Statement?
Think of a selection statement as a traffic light 🚦 that decides which direction a program should go based on conditions.
- if – choose one path if a condition is true.
- else if – check another condition if the first one fails.
- else – the fallback path when all previous conditions are false.
What is an Iteration Statement?
Iteration is like a repeating chore list 🗒️. The program keeps doing something until a condition changes.
- while – repeat while a condition is true.
- do-while – repeat at least once, then check the condition.
- for – loop a set number of times or over a collection.
Nested Selection Inside a Loop
Imagine you’re sorting a deck of cards. For each card you check its suit and then its rank.
Example (pseudo‑code):
for (int i = 0; i < deckSize; i++) {
if (deck[i].suit == "Hearts") {
if (deck[i].rank == "Ace") {
// Special action for Ace of Hearts
} else {
// Other hearts
}
} else {
// Non‑hearts
}
}
Here, the if inside the for loop is a nested selection.
Nested Loops (Iteration Inside Iteration)
Think of a grid of seats in a stadium. You need to visit every seat: first row, then seat, then next row, etc.
Example (pseudo‑code):
for (int row = 1; row <= totalRows; row++) {
for (int seat = 1; seat <= seatsPerRow; seat++) {
// Process seat (row, seat)
}
}
This double for loop is a classic nested iteration.
Combining Both: Nested Selection Inside Nested Loops
Example: Find all prime numbers up to 100.
for (int num = 2; num <= 100; num++) {
bool isPrime = true;
for (int div = 2; div <= sqrt(num); div++) {
if (num % div == 0) {
isPrime = false;
break; // stop checking further divisors
}
}
if (isPrime) {
// num is prime
}
}
Here, the if inside the inner for loop is a nested selection, and the inner for itself is inside the outer for loop.
Exam Tips 📚
- Always check the order of conditions in nested if-else chains.
- Remember that a break exits the innermost loop only.
- Use comments to label each level of nesting; it helps during marking.
- When writing for loops, ensure the initialisation, condition, and increment are correctly placed.
- Practice writing nested loops that produce matrices or patterns; they often appear in exam questions.
Quick Recap with Math
Nested loops can calculate sums like:
$$S = \sum_{i=1}^{n} \sum_{j=1}^{m} a_{ij}$$
Here, the outer sum runs over rows and the inner sum over columns.
Revision
Log in to practice.