Can any WHILE Loop be replaced with a FOR loop?

125 ビュー (過去 30 日間)
Dylan
Dylan 2011 年 11 月 1 日
I had a test in my computer science course in which I was asked if any while loop can be replaced with a for loop. I put true. I guess the answer was false. My professor said that if you had a while loop in which you asked the user to input a certain value that had to be within a certain range and kept on iterating over the loop until the user inputted a value within the range that you wouldn't be able to do this with a for loop.
I however thought that any for loop can be written with a while loop and any while loop can be rewritten with a for loop. I think I may have even read something about this in my textbook but am unable to come up away with doing what my professor said with a for loop but believe that it's possible. Can anyone please come up with a way to do such a thing with a for loop?
for example a while loop
A=0;
while A<1
x=input('Enter a value');
if x>4 && x<10
A=1
else
end
this would force the user to enter a number between 4 and 10, not including 4 and 10, and would just keep on iterating over the loop until the user does.
  1 件のコメント
Dylan
Dylan 2011 年 11 月 1 日
I even found this in my book and believe this is why I thought it was possible
"Any problem that can be solved using a while loop could also be solved using a for loop"

サインインしてコメントする。

回答 (3 件)

Fangjun Jiang
Fangjun Jiang 2011 年 11 月 1 日
In a twisted way:
for k=1:inf
x=input('Enter a value');
if x>4 && x<10
break;
end
end

Alex
Alex 2011 年 11 月 1 日
Another option, so your computer does eventually crash (as k gets to large).
for k = 1:2
if(stuff)
break;
else
k = k - 1;
end
end
Keep in mind, it is not good programming to modify the loop variable within the loop, but it does work
  1 件のコメント
Walter Roberson
Walter Roberson 2011 年 11 月 1 日
In MATLAB, modifying the loop variable within a loop only affects the loop variable until the next iteration; upon starting the next iteration, the loop variable will be assigned whatever value it would normally have been as if you had not had any modification statements.

サインインしてコメントする。


Walter Roberson
Walter Roberson 2011 年 11 月 1 日
There are definitely while loops that cannot be done in any "for" loop with a fixed finite number of iterations. See for example http://en.wikipedia.org/wiki/Collatz_conjecture where the termination condition (N becoming 1) has not been proven to always occur.
If every loop could be executed within a fixed maximum number of steps, then the theoretically very important http://en.wikipedia.org/wiki/Halting_problem would have a positive solution, but it has been proven by way of contradiction that that cannot exist.

Community Treasure Hunt

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

Start Hunting!

Translated by