0
I am in need of an explanation on how to turn a structure into while to for and vice versa. I thank anyone who can help!
0
I am in need of an explanation on how to turn a structure into while to for and vice versa. I thank anyone who can help!
4
Since you did not define the language in the question, follow a "generic" example that iterates from 1 to 10:
for( i = 1; i <= 10; i++ ) {
... conteudo ...
}
Equivalent with while
:
i = 1;
while( i <= 10 ) {
... conteudo ...
i++;
}
Basically, the for
is composed of 3 parts in its definition:
for( inicializacao; teste para determinar se executa; operação ao final de cada iteração )
The while
is a "lean" version of the for:
while( teste para determinar se executa )
Therefore, the other two situations that the for
has the most must be done before the while
and within its execution block.
Now, what can complicate, is when you have interruptions/flow changes, with continue
, break
and equivalents. See a little more about this in this answer:
Other considerations:
We still have the do ... while
, that can be seen here:
And in Lua we also have the repeat
:
What is the difference between repeat and while on the moon?
It would be good to put a body in the loop, to make clear (in the example, in the text is already good) that the i++
has to be the last thing on while
.
eventually that while(cond){A}
= for( ; cond ; ){A}
@mgibsonbr will improve on several aspects. I even understand the i++ can be anywhere from the while since not used in the loop, but I understood what you said. And there are other improvements needed, I want to see if break, continue etc, and what you mentioned in your comment I clarify better in the next issue.
Browser other questions tagged algorithm while for loop
You are not signed in. Login or sign up in order to post.
How so? If you understand well how the two work, you will know how to adapt any problem in the two solutions
– mau humor
Explain the reason better. You simply want to know how to make one to run as a while, and while to run as a for, or you want to know how to restructure a repeat for the most correct structure?
– Gabriel Katakura
Has some specific language?
– Randrade
Please specify a language (each language has different means of making one
for
,while
is already more standardized but still there may be discrepancies), and also show what you already know about these structures and what still remains to be known. Give an example of code, if possible. The way it is, it’s hard to know what you’re asking, but these adjustments can make the question more focused (and "responsive").– mgibsonbr