Challenge - 5 Problems
Loop Control Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of break in a for loop
What is the output of this MATLAB code?
for i = 1:5
if i == 3
break;
end
disp(i)
endMATLAB
for i = 1:5 if i == 3 break; end disp(i) end
Attempts:
2 left
💡 Hint
The break statement stops the loop immediately when the condition is met.
✗ Incorrect
The loop prints numbers starting from 1. When i equals 3, the break stops the loop before printing 3. So only 1 and 2 are printed.
❓ Predict Output
intermediate2:00remaining
Output of continue in a for loop
What is the output of this MATLAB code?
for i = 1:5
if i == 3
continue;
end
disp(i)
endMATLAB
for i = 1:5 if i == 3 continue; end disp(i) end
Attempts:
2 left
💡 Hint
The continue statement skips the current iteration when the condition is met.
✗ Incorrect
When i equals 3, continue skips the disp(i) command, so 3 is not printed. All other numbers are printed.
🔧 Debug
advanced2:00remaining
Identify the error in break usage
What error does this MATLAB code produce?
if true
break;
endMATLAB
if true break; end
Attempts:
2 left
💡 Hint
Break can only be used inside loops in MATLAB.
✗ Incorrect
The break statement must be inside a loop. Using it inside an if statement without a loop causes a syntax error.
❓ Predict Output
advanced2:00remaining
Nested loops with break and continue
What is the output of this MATLAB code?
for i = 1:3
for j = 1:3
if j == 2
break;
end
fprintf('[%%d %%d]\n',i,j)
end
endMATLAB
for i = 1:3 for j = 1:3 if j == 2 break; end fprintf('[%d %d]\n',i,j) end end
Attempts:
2 left
💡 Hint
The break stops the inner loop when j equals 2, so only j=1 is displayed for each i.
✗ Incorrect
For each i, the inner loop runs j=1 and prints [i 1]. When j=2, break stops the inner loop. So only [1 1], [2 1], and [3 1] are printed.
❓ Predict Output
expert3:00remaining
Complex loop control with break and continue
What is the output of this MATLAB code?
count = 0;
for i = 1:5
if mod(i,2) == 0
continue;
end
count = count + 1;
if count == 3
break;
end
disp(i)
endMATLAB
count = 0; for i = 1:5 if mod(i,2) == 0 continue; end count = count + 1; if count == 3 break; end disp(i) end
Attempts:
2 left
💡 Hint
Count only increases for odd numbers. When count reaches 3, break executes before disp(i).
✗ Incorrect
The loop skips even numbers. For odd i, count increases. When count reaches 3 (at i=5), break stops the loop before printing 5. So only 1 and 3 are printed.