Challenge - 5 Problems
For Loop Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a simple for loop with indexing
What is the output of the following MATLAB code?
MATLAB
sumVal = 0; for i = 1:4 sumVal = sumVal + i; end sumVal
Attempts:
2 left
💡 Hint
Think about adding numbers from 1 to 4 step by step.
✗ Incorrect
The loop adds 1 + 2 + 3 + 4 which equals 10.
❓ Predict Output
intermediate2:00remaining
For loop with decrementing index
What will be the value of variable 'result' after running this code?
MATLAB
result = 1; for k = 5:-1:2 result = result * k; end
Attempts:
2 left
💡 Hint
Multiply numbers from 5 down to 2.
✗ Incorrect
The loop multiplies 5*4*3*2 = 120.
🔧 Debug
advanced2:00remaining
Identify the error in this for loop
What error does this MATLAB code produce?
MATLAB
total = 0; for i = 1 5 total = total + i; end
Attempts:
2 left
💡 Hint
Check the for loop range syntax carefully.
✗ Incorrect
The for loop range must use a colon (1:5), not a space.
❓ Predict Output
advanced2:00remaining
Nested for loops output
What is the value of 'count' after running this nested loop?
MATLAB
count = 0; for i = 1:3 for j = 1:2 count = count + 1; end end
Attempts:
2 left
💡 Hint
Multiply the number of iterations of both loops.
✗ Incorrect
Outer loop runs 3 times, inner loop 2 times, total 3*2=6 increments.
🧠 Conceptual
expert2:00remaining
Effect of modifying loop variable inside for loop
Consider this MATLAB code. What is the final value of 'x' after the loop finishes?
MATLAB
x = 0; for i = 1:4 x = x + i; i = 10; end
Attempts:
2 left
💡 Hint
Changing the loop variable inside the loop does not affect the iteration.
✗ Incorrect
The loop variable 'i' is controlled by the for loop and resetting it inside does not change the sequence. So x sums 1+2+3+4=10.