Current Affairs updated daily
KalviGavaniKalviGavani

PHP Looping Structure Exercise Solutions | KalviGavani

Samacheer Kalvi Class 12 Computer Applications Chapter 7 Looping Structure exercise solutions — for, while, do-while, foreach loops, break, continue, nested loops with worked PHP examples and exam tips.

Updated 13 June 202615 min read

Exercise Solutions Available

Step-by-step answers for all textbook questions in this chapter

View Solutions →

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) or foreach ($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; and continue N; where N specifies how many levels of nested loops to break/continue out of.

I. Choose the Best Answer (MCQs)

1. Which loop in PHP is guaranteed to execute at least once?
Answer

(a) for &nbsp;&nbsp; (b) while &nbsp;&nbsp; (c) do-while &nbsp;&nbsp; (d) foreach

Answer(c) do-while

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.


2. What is the output of the following code?
<?php
for ($i = 1; $i <= 3; $i++) {
    echo $i . " ";
}
?>
Answer

(a) 1 2 &nbsp;&nbsp; (b) 1 2 3 &nbsp;&nbsp; (c) 0 1 2 &nbsp;&nbsp; (d) 1 2 3 4

Answer(b) 1 2 3

Explanation: The loop starts at 1, increments by 1, and stops when $i becomes 4 (condition fails).


3. The break statement is used to:
Answer

(a) Skip the current iteration &nbsp;&nbsp; (b) Exit the loop entirely &nbsp;&nbsp; (c) Restart the loop &nbsp;&nbsp; (d) Pause execution

Answer(b) Exit the loop entirely

Explanation: break terminates the loop and control passes to the statement after the loop. Use continue to skip one iteration.


4. Which loop is best suited for iterating over an associative array?
Answer

(a) for &nbsp;&nbsp; (b) while &nbsp;&nbsp; (c) do-while &nbsp;&nbsp; (d) foreach

Answer(d) foreach

Explanation: foreach automatically extracts each key-value pair, making it ideal for associative arrays without needing to track an index.


5. What happens if you forget the increment in a for loop?
for ($i = 1; $i <= 5; ) {
    echo $i;
}
Answer

(a) Prints 12345 &nbsp;&nbsp; (b) Prints 1 &nbsp;&nbsp; (c) Infinite loop &nbsp;&nbsp; (d) Error

Answer(c) Infinite loop

Explanation: Without incrementing $i, the condition $i <= 5 is always true, causing the loop to run forever.


6. What does continue 2; do inside a nested loop?
Answer

(a) Continues the outer loop's next iteration &nbsp;&nbsp; (b) Continues the inner loop twice &nbsp;&nbsp; (c) Exits both loops &nbsp;&nbsp; (d) Throws an error

Answer(a) Continues the outer loop's next iteration

Explanation: The numeric argument tells PHP how many levels of enclosing loops to affect. continue 2 affects the outer loop.


7. Which of the following is the correct syntax for a foreach loop with both key and value?
Answer

(a) foreach ($arr as $v) &nbsp;&nbsp; (b) foreach ($arr => $k as $v) &nbsp;&nbsp; (c) foreach ($arr as $k => $v) &nbsp;&nbsp; (d) foreach ($k => $v from $arr)

Answer(c) foreach ($arr as $k => $v)

Explanation: The correct syntax is foreach ($array as $key => $value), which gives you both the key and value on each iteration.


8. What is the output?
<?php
$x = 0;
while ($x < 2) {
    $x++;
    if ($x == 1) continue;
    echo $x . " ";
}
?>
Answer

(a) 1 &nbsp;&nbsp; (b) 2 &nbsp;&nbsp; (c) 1 2 &nbsp;&nbsp; (d) 0 1 2

Answer(b) 2

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.


9. In a nested for loop, how many times does the inner loop execute if the outer runs 3 times and the inner runs 4 times per outer iteration?
Answer

(a) 3 &nbsp;&nbsp; (b) 4 &nbsp;&nbsp; (c) 7 &nbsp;&nbsp; (d) 12

Answer(d) 12

Explanation: The inner loop executes 4 times for each of the 3 outer iterations: 3 x 4 = 12 total inner iterations.


10. Which loop should you use when the number of iterations is unknown beforehand?
Answer

(a) for &nbsp;&nbsp; (b) foreach &nbsp;&nbsp; (c) while or do-while &nbsp;&nbsp; (d) None of these

Answer(c) while or do-while

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 ANo.Column B
1fordCounter-controlled loop
2whileeEntry-controlled loop
3do-whileaExit-controlled loop
4foreachcArray iteration loop
5breakbTerminates the loop

Set B

No.Column ANo.Column B
1continuedSkips current iteration
2infinite loopeCondition never becomes false
3nested loopaLoop inside a loop
4break 2cExits two loop levels
5$i++bIncrement operator

V. Short Answer Questions

1. Explain the syntax and working of the for loop in PHP.
Answer

The for loop has three expressions in its header: initialisation, condition, and increment.

for (initialisation; condition; increment) {
    // loop body
}
Working(1) The initialisation runs once. (2) The condition is checked; if true, the body executes. (3) After the body, the increment runs. (4) Go back to step 2. The loop stops when the condition becomes false.

Example:

<?php
for ($i = 1; $i <= 5; $i++) {
    echo $i . " ";   // Output: 1 2 3 4 5
}
?>
2. Differentiate between while and do-while loops.
Answer
Featurewhiledo-while
Condition checkBefore loop body (entry-controlled)After loop body (exit-controlled)
Minimum executionsZero (may not execute at all)One (always executes at least once)
Syntaxwhile (condition) { ... }do { ... } while (condition);
Use caseWhen execution may not be neededWhen body must run at least once
3. What is the purpose of the foreach loop? Give an example.
Answer

The foreach loop is designed to iterate over arrays without manually tracking an index or condition. It automatically moves through each element.

<?php
$colors = array("Red", "Green", "Blue");
foreach ($colors as $color) {
    echo $color . " ";   // Output: Red Green Blue
}

// With key-value pairs
$marks = array("Tamil" => 90, "English" => 85);
foreach ($marks as $subject => $mark) {
    echo "$subject: $mark\n";
}
// Output: Tamil: 90  English: 85
?>
4. Write a PHP program to print the multiplication table of 7.
<?php
$num = 7;
for ($i = 1; $i <= 10; $i++) {
    echo "$num x $i = " . ($num * $i) . "<br>";
}
?>
Answer

Output: 7x1=7, 7x2=14, ... , 7x10=70

5. Explain break and continue with examples.
Answer

break — exits the loop entirely:

<?php
for ($i = 1; $i <= 10; $i++) {
    if ($i == 5) break;
    echo $i . " ";   // Output: 1 2 3 4
}
?>

continue — skips the current iteration and moves to the next:

<?php
for ($i = 1; $i <= 5; $i++) {
    if ($i == 3) continue;
    echo $i . " ";   // Output: 1 2 4 5
}
?>

VI. Detailed Answer Questions

1. Explain all four loop constructs in PHP with syntax and example for each.
Answer

for loop — used when the number of iterations is known:

for ($i = 1; $i <= 5; $i++) {
    echo $i;    // 12345
}

while loop — entry-controlled; runs while condition is true:

$i = 1;
while ($i <= 5) {
    echo $i;    // 12345
    $i++;
}

do-while loop — exit-controlled; body executes at least once:

$i = 1;
do {
    echo $i;    // 12345
    $i++;
} while ($i <= 5);

foreach loop — iterates over arrays:

$arr = array(10, 20, 30);
foreach ($arr as $val) {
    echo $val;  // 10 20 30
}

Each loop type serves a different purpose: for for known iterations, while/do-while for unknown iterations, and foreach for array traversal.


2. What are nested loops? Write a PHP program to print a star pattern using nested loops.
Answer

A nested loop is a loop placed inside another loop. The inner loop completes all its iterations for each single iteration of the outer loop.

<?php
// Print a right-angled triangle star pattern
for ($i = 1; $i <= 5; $i++) {        // outer loop: rows
    for ($j = 1; $j <= $i; $j++) {    // inner loop: stars per row
        echo "* ";
    }
    echo "<br>";                       // new line after each row
}
?>

Output:

* * * * * * * * * * * * * * *

Important: The outer loop controls the number of rows; the inner loop controls what is printed in each row. Changing the inner loop condition changes the pattern shape.


3. Write a PHP program to find the sum of the first 100 natural numbers using (a) for loop and (b) while loop.
Answer

(a) Using for loop:

<?php
$sum = 0;
for ($i = 1; $i <= 100; $i++) {
    $sum += $i;
}
echo "Sum = $sum";   // Output: Sum = 5050
?>

(b) Using while loop:

<?php
$sum = 0;
$i = 1;
while ($i <= 100) {
    $sum += $i;
    $i++;
}
echo "Sum = $sum";   // Output: Sum = 5050
?>

Both produce the same result: 5050. The formula n(n+1)/2 gives 100(101)/2 = 5050, which verifies our answer.


4. Explain the difference between break and continue with practical scenarios.
Answer
Featurebreakcontinue
ActionExits the loop completelySkips only the current iteration
Next stepExecution continues after the loopNext iteration begins
In switchExits the switch blockCannot be used in switch
With numberbreak 2 exits 2 nested levelscontinue 2 continues the outer loop

Practical scenario — break: Search for a number in an array; once found, no need to continue:

<?php
$arr = array(5, 12, 8, 3, 20);
$search = 8;
foreach ($arr as $val) {
    if ($val == $search) {
        echo "Found $search!";
        break;
    }
}
?>

Practical scenario — continue: Print only odd numbers from 1 to 10:

<?php
for ($i = 1; $i <= 10; $i++) {
    if ($i % 2 == 0) continue;   // skip even numbers
    echo $i . " ";               // Output: 1 3 5 7 9
}
?>

5. Write a PHP program to find the factorial of a number using a loop.
<?php
$num = 5;
$fact = 1;

for ($i = 1; $i <= $num; $i++) {
    $fact *= $i;
}

echo "Factorial of $num = $fact";   // Output: Factorial of 5 = 120
?>
ExplanationFactorial of 5 = 5 x 4 x 3 x 2 x 1 = 120. The loop multiplies $fact by each number from 1 to $num.

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 break and continue with practical examples
  • [ ] Can write nested loop programs (star patterns, multiplication tables)
  • [ ] Understand break N and continue N for 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

Frequently Asked Questions

for, while, do-while, and foreach are the four loop constructs in PHP.