How to transform a while structure in for? And vice versa? [closed]

0

I'm needing an explanation on how to transform a structure in while to for and vice versa. Thanks in advance for any help!

    
asked by anonymous 28.04.2016 / 04:02

1 answer

3

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:

  

Should I use break in for?

Other considerations:

We also have do ... while , which can be seen here:

  

What is the usefulness and importance of "do ... while"?

And in Lua we also have repeat :

  

What is the difference between repeat and while on the moon?

    
28.04.2016 / 05:42