MATLAB Answers

# Why does a for-loop stop at the correct place when you use the same counter name as your upper limit?

4 views (last 30 days)
Kathryn Moore on 24 Apr 2018
Answered: Ahmet Cecen on 24 Apr 2018
Why does this code work, and display the numbers 1-7, rather than stopping at r=1 or going on infinitely (for each step, r=r and the loop continues)?
r=7;
for r=1:r
disp(r)
end
##### 0 CommentsShowHide -1 older comments

Sign in to comment.

### Answers (1)

Ahmet Cecen on 24 Apr 2018
Because the upper limit is evaluated at the beginning of the execution when r = 7. If you want the loop condition to be evaluated every time the loop iterates, you need to use a while loop. See even if you did something like this:
r=7;
for r=1:r
r=5;
disp(r)
end
You would still get 7 iterations. However now we are overwriting the iterator so you would only get 5s.
##### 0 CommentsShowHide -1 older comments

Sign in to comment.

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by