Challenge - 5 Problems
While Loop Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a simple while loop
What is the output of this MATLAB code?
MATLAB
i = 1; while i <= 3 disp(i) i = i + 1; end
Attempts:
2 left
💡 Hint
The loop runs while i is less than or equal to 3, increasing i by 1 each time.
✗ Incorrect
The loop starts with i=1 and prints i. It increments i by 1 each time until i becomes 4, which stops the loop. So it prints 1, 2, and 3.
❓ Predict Output
intermediate2:00remaining
Sum calculation using while loop
What is the value of variable sum after running this code?
MATLAB
sum = 0; i = 1; while i <= 5 sum = sum + i; i = i + 1; end
Attempts:
2 left
💡 Hint
The loop adds numbers from 1 to 5 to sum.
✗ Incorrect
The loop adds 1 + 2 + 3 + 4 + 5 = 15 to sum.
🔧 Debug
advanced2:00remaining
Identify the error in this while loop
What error does this MATLAB code produce when run?
MATLAB
i = 1; while i < 5 disp(i) % missing increment of i end
Attempts:
2 left
💡 Hint
Check if the loop variable changes inside the loop.
✗ Incorrect
Since i is never increased, the condition i < 5 is always true, causing an infinite loop.
❓ Predict Output
advanced2:00remaining
While loop with break statement
What is the output of this MATLAB code?
MATLAB
i = 1; while true disp(i) if i == 3 break end i = i + 1; end
Attempts:
2 left
💡 Hint
The loop stops when i equals 3.
✗ Incorrect
The loop prints i starting from 1. When i reaches 3, the break stops the loop, so output is 1, 2, 3.
🧠 Conceptual
expert2:00remaining
Number of iterations in nested while loops
How many times will the inner disp statement run in this MATLAB code?
MATLAB
i = 1; count = 0; while i <= 3 j = 1; while j <= 2 disp([i, j]) count = count + 1; j = j + 1; end i = i + 1; end
Attempts:
2 left
💡 Hint
Multiply the number of outer loop runs by inner loop runs.
✗ Incorrect
Outer loop runs 3 times, inner loop runs 2 times each, so total is 3*2=6.