Bird
0
0

Identify the error in this PowerShell for loop:

medium📝 Debug Q7 of 15
PowerShell - Control Flow

Identify the error in this PowerShell for loop:

for ($i=0; $i -lt 5; $i--) { Write-Output $i }
AThe loop body is missing curly braces
BThe condition operator <code>-lt</code> is invalid
CThe initialization <code>$i=0</code> is incorrect
DThe increment operator should be <code>$i++</code> instead of <code>$i--</code>
Step-by-Step Solution
Solution:
  1. Step 1: Understand loop direction

    The loop starts at 0 and should run while $i is less than 5.
  2. Step 2: Check increment/decrement

    Using $i-- decreases $i, which will never reach 5, causing an infinite loop.
  3. Step 3: Correct increment

    It should be $i++ to increase $i and eventually end the loop.
  4. Final Answer:

    The increment operator should be $i++ instead of $i-- -> Option D
  5. Quick Check:

    Increment must match loop condition direction [OK]
Quick Trick: Increment matches condition direction [OK]
Common Mistakes:
  • Using decrement when condition expects increment
  • Misunderstanding loop termination
  • Ignoring infinite loop risk

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PowerShell Quizzes