Recall & Review
beginner
What is a while loop in MATLAB?
A while loop in MATLAB repeats a block of code as long as a given condition is true. It checks the condition before each repetition.
Click to reveal answer
beginner
How do you write a basic while loop in MATLAB?
Use the syntax:<br>
while condition
% code to repeat
end<br>The loop runs while the condition is true.Click to reveal answer
beginner
What happens if the condition in a while loop is initially false?
The code inside the while loop does not run at all because the condition is checked before the first iteration.
Click to reveal answer
intermediate
How can you avoid an infinite while loop in MATLAB?
Make sure the condition will eventually become false by changing variables inside the loop. Otherwise, the loop runs forever.
Click to reveal answer
beginner
Example: What does this MATLAB code print?<br>
i = 1;
while i <= 3
disp(i)
i = i + 1;
endIt prints:<br>1<br>2<br>3<br>Because the loop runs while i is 1, 2, and 3, then stops when i becomes 4.
Click to reveal answer
What does the while loop check before each repetition?
✗ Incorrect
A while loop checks the condition before each repetition to decide if it should continue running.
What happens if the condition in a while loop never becomes false?
✗ Incorrect
If the condition never becomes false, the while loop runs forever, causing an infinite loop.
Which keyword ends a while loop in MATLAB?
✗ Incorrect
In MATLAB, the keyword 'end' is used to close a while loop block.
What will this code print?<br>i = 5;<br>while i < 3<br>disp(i)<br>i = i + 1;<br>end
✗ Incorrect
Since the condition i < 3 is false at the start (i=5), the loop does not run and prints nothing.
How can you make sure a while loop eventually stops?
✗ Incorrect
To avoid infinite loops, you must change the variable in the condition inside the loop so it eventually becomes false.
Explain how a while loop works in MATLAB and give a simple example.
Think about how you repeat a task until something changes.
You got /3 concepts.
Describe how to prevent an infinite loop when using while loops.
What must happen inside the loop to stop it?
You got /3 concepts.