Bird
0
0

Identify the error in this PHP for loop:

medium📝 Debug Q6 of 15
PHP - Loops
Identify the error in this PHP for loop:
for ($k = 0; $k < 4; $k + 2) {
    echo $k;
}
AThe initialization should be $k = 1
BThe loop condition should be $k <= 4
CThe increment expression should be $k += 2, not $k + 2
DThe echo statement is missing a semicolon
Step-by-Step Solution
Solution:
  1. Step 1: Check increment part

    The increment expression '$k + 2' does not update $k; it just evaluates an expression.
  2. Step 2: Correct increment syntax

    Use '$k += 2' to increment $k by 2 each iteration.
  3. Final Answer:

    The increment expression should be $k += 2, not $k + 2 -> Option C
  4. Quick Check:

    Increment must update variable [OK]
Quick Trick: Increment must modify loop variable [OK]
Common Mistakes:
  • Using '+' instead of '+=' in increment
  • Confusing condition operators
  • Ignoring variable update in increment

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes