0
0
MATLABdata~20 mins

While loops in MATLAB - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
While Loop Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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
A
2
3
4
B
1
2
3
4
C
1
2
3
D
1
2
Attempts:
2 left
💡 Hint
The loop runs while i is less than or equal to 3, increasing i by 1 each time.
Predict Output
intermediate
2: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
A15
B10
C5
D0
Attempts:
2 left
💡 Hint
The loop adds numbers from 1 to 5 to sum.
🔧 Debug
advanced
2: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
ASyntax error: missing end statement
BInfinite loop (program never stops)
CRuntime error: variable i undefined
DOutputs numbers 1 to 4 then stops
Attempts:
2 left
💡 Hint
Check if the loop variable changes inside the loop.
Predict Output
advanced
2: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
A
1
2
3
B
1
2
C
1
2
3
4
DInfinite loop with no output
Attempts:
2 left
💡 Hint
The loop stops when i equals 3.
🧠 Conceptual
expert
2: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
A2
B5
C3
D6
Attempts:
2 left
💡 Hint
Multiply the number of outer loop runs by inner loop runs.