Exercise Solutions Available
Step-by-step answers for all textbook questions in this chapter
Chapter 7 — Looping Structure: Exercise Solutions Guide
How to Use This Page
1. Attempt every exercise on your own before reading the solutions. 2. Compare your method with the answer shown — focus on the logic, not just the final output. 3. Re-write tricky code snippets by hand at least once; muscle memory helps in the exam hall.
Key Concepts (Quick Recap)
- A loop repeats a block of code while a condition is true.
- for loop — best when you know exactly how many times to iterate (
for ($i=1; $i<=10; $i++)). - while loop — checks the condition before each iteration; may execute zero times.
- do-while loop — checks the condition after each iteration; guaranteed to execute at least once.
- foreach loop — designed for iterating over arrays; syntax:
foreach ($arr as $value)orforeach ($arr as $key => $value). - break — immediately exits the nearest enclosing loop (or switch).
- continue — skips the rest of the current iteration and jumps to the next iteration.
- Nested loops — a loop inside another loop; the inner loop completes all its iterations for each outer-loop iteration.
- Infinite loop — occurs when the loop condition never becomes false (e.g.,
while(true)without a break). - Loop initialisation, condition, and increment/decrement are the three essential parts of any counter-controlled loop.
- PHP also supports
break N;andcontinue N;where N specifies how many levels of nested loops to break/continue out of.
I. Choose the Best Answer (MCQs)
Explanation: In a do-while loop, the body executes before the condition is tested, so it always runs at least once even if the condition is initially false.
<?php
for ($i = 1; $i <= 3; $i++) {
echo $i . " ";
}
?>
Explanation: The loop starts at 1, increments by 1, and stops when $i becomes 4 (condition fails).
break statement is used to:Explanation: break terminates the loop and control passes to the statement after the loop. Use continue to skip one iteration.
Explanation: foreach automatically extracts each key-value pair, making it ideal for associative arrays without needing to track an index.
for ($i = 1; $i <= 5; ) {
echo $i;
}
Explanation: Without incrementing $i, the condition $i <= 5 is always true, causing the loop to run forever.
continue 2; do inside a nested loop?Explanation: The numeric argument tells PHP how many levels of enclosing loops to affect. continue 2 affects the outer loop.
Explanation: The correct syntax is foreach ($array as $key => $value), which gives you both the key and value on each iteration.
<?php
$x = 0;
while ($x < 2) {
$x++;
if ($x == 1) continue;
echo $x . " ";
}
?>
Explanation: When $x is 1, continue skips the echo. The loop runs again with $x = 2, which is printed, then the condition $x < 2 becomes false.
Explanation: The inner loop executes 4 times for each of the 3 outer iterations: 3 x 4 = 12 total inner iterations.
Explanation: while and do-while are condition-driven loops ideal when you don't know in advance how many times to repeat.
II. Fill in the Blanks
1. The three parts of a for loop are initialisation, condition, and increment/decrement.
2. The break statement is used to exit the loop immediately.
3. The continue statement skips the remaining statements in the current iteration and moves to the next iteration.
4. A loop placed inside another loop is called a nested loop.
5. In a do-while loop, the condition is checked at the end of the loop body.
6. The foreach loop is specifically designed to iterate over arrays.
7. break 2; will exit two levels of nested loops.
8. If the loop condition is always true and there is no break, it results in an infinite loop.
9. The syntax for foreach with only values is foreach ($array as $value).
10. In for ($i=0; $i<10; $i+=2), the loop executes 5 times.
III. True or False
1. A while loop always executes at least once. — False. A while loop checks the condition first; if it is false initially, the body never executes. Use do-while for at-least-once execution.
2. The break statement can be used inside for, while, do-while, and switch. — True.
3. continue can be used only inside loops, not inside switch. — True. (Unlike break, continue has no meaning inside a switch statement.)
4. A for loop can be written without all three expressions in the header. — True. All three parts of for(;;) are optional; for(;;) creates an infinite loop.
5. The foreach loop works with objects as well as arrays. — True. In PHP, foreach can iterate over objects that implement Iterator or have public properties.
6. In a nested loop, break without a number exits only the innermost loop. — True. break exits the nearest enclosing loop; use break 2 to exit the outer loop as well.
7. do-while and while always produce the same output. — False. They differ when the condition is initially false — while skips the body, do-while executes it once.
8. The increment expression in a for loop is executed before the loop body. — False. The increment runs after the loop body, before the next condition check.
9. foreach ($arr as $key => $val) works only for associative arrays. — False. It works for both indexed and associative arrays. For indexed arrays, the key is the numeric index.
10. You can use break inside an if statement (not inside a loop or switch). — False. break is only meaningful inside loops or switch; it causes an error if used inside an if that is not within a loop/switch.
IV. Match the Following
Set A
| No. | Column A | No. | Column B |
|---|---|---|---|
| 1 | for | d | Counter-controlled loop |
| 2 | while | e | Entry-controlled loop |
| 3 | do-while | a | Exit-controlled loop |
| 4 | foreach | c | Array iteration loop |
| 5 | break | b | Terminates the loop |
Set B
| No. | Column A | No. | Column B |
|---|---|---|---|
| 1 | continue | d | Skips current iteration |
| 2 | infinite loop | e | Condition never becomes false |
| 3 | nested loop | a | Loop inside a loop |
| 4 | break 2 | c | Exits two loop levels |
| 5 | $i++ | b | Increment operator |
V. Short Answer Questions
Example:
<?php
for ($i = 1; $i <= 5; $i++) {
echo $i . " "; // Output: 1 2 3 4 5
}
?>
<?php
$num = 7;
for ($i = 1; $i <= 10; $i++) {
echo "$num x $i = " . ($num * $i) . "<br>";
}
?>
VI. Detailed Answer Questions
break and continue with practical scenarios.<?php
$num = 5;
$fact = 1;
for ($i = 1; $i <= $num; $i++) {
$fact *= $i;
}
echo "Factorial of $num = $fact"; // Output: Factorial of 5 = 120
?>
Common Mistakes
1. Forgetting to increment the counter in a while/do-while loop — causes an infinite loop. Always include $i++ or similar inside the loop body.
2. Using = instead of == in a condition — while ($i = 5) is an assignment (always true), not a comparison. Use while ($i == 5).
3. Off-by-one errors — Starting at 0 vs 1, or using < vs <=. Decide your range first, then choose the operator.
4. Confusing break and continue — break exits the loop; continue only skips one iteration. Mixing them up changes the entire output.
5. Not initialising the accumulator variable — $sum = 0; must be set before the loop, otherwise $sum += $i starts from NULL/undefined.
6. Misplacing the semicolon after a while condition — while ($i < 5); creates an empty body loop, which is likely infinite.
7. Using foreach on a non-array — foreach works only on arrays and objects; passing a string or integer causes a warning.
Exam Checklist
- [ ] Can write the syntax of all four loop types (for, while, do-while, foreach) from memory
- [ ] Can explain entry-controlled vs exit-controlled loops with examples
- [ ] Know the difference between
breakandcontinuewith practical examples - [ ] Can write nested loop programs (star patterns, multiplication tables)
- [ ] Understand
break Nandcontinue Nfor multi-level loop control - [ ] Can trace loop output for a given code snippet (dry run)
- [ ] Can write programs for sum of series, factorial, Fibonacci, etc.
- [ ] Know when to use each loop type (for: known count, while: unknown count, foreach: arrays)
- [ ] Can identify and fix infinite loop scenarios
- [ ] Understand the role of initialisation, condition, and increment in loop control
