How can I avoid infinite while loop?
Show older comments
N = 1; while (N<11) n = ((N*2)+(N+1))/N; N = n end
I wish to assign the value of 'n' to 'N' and compare if it's less than '11' and again enter the loop until 'N' is equal to 11. Please help.
Accepted Answer
More Answers (2)
Daniel
on 11 Jul 2014
Set a number equal to the number of times you want to loop (this case I chose 11), subtract each time you're in the loop, and add an and condition
LOOP_LIMIT = 11;
N = 1;
while (N < 11 && LOOP_LIMIT > 0)
n = ((N*2)+(N+1))/N;
N = n;
LOOP_LIMIT = LOOP_LIMIT-1;
end
1 Comment
Shashanka
on 11 Jul 2014
C.J. Harris
on 11 Jul 2014
Edited: C.J. Harris
on 11 Jul 2014
0 votes
You have an infinity loop because your seed (N) is starting at one. Note that your equation ((N*2)+(N+1))/N is in fact equal to 3+(1/N), thereby meaning you'll only get 11 (or greater) for values less than 0.125.
Not sure why you even need a loop, can't you just rearrange, therefore getting n = 1/(11-3) = 0.125.
1 Comment
Shashanka
on 11 Jul 2014
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

