I'm needing an explanation on how to transform a structure in while to for and vice versa. Thanks in advance for any help!
I'm needing an explanation on how to transform a structure in while to for and vice versa. Thanks in advance for any help!
As you did not define the language in the question, a generic example that iterates from 1 to 10 follows:
for( i = 1; i <= 10; i++ ) {
... conteudo ...
}
Equivalent to while
:
i = 1;
while( i <= 10 ) {
... conteudo ...
i++;
}
Basically, for
is composed of 3 parts in its definition:
for( inicializacao; teste para determinar se executa; operação ao final de cada iteração )
while
is a "lean" version of for:
while( teste para determinar se executa )
Therefore, the other two situations that for
has the most must be done before while
and within its execution block.
Now, what can be complicated is when you have interruptions / changes of flow, with continue
, break
and equivalents. See a little more about this in this answer:
Other considerations:
We also have do ... while
, which can be seen here:
And in Lua we also have repeat
:
What is the difference between repeat and while on the moon?