How to transform a while structure into for? And vice versa?

Asked

Viewed 1,432 times

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!

  • How so? If you understand well how the two work, you will know how to adapt any problem in the two solutions

  • 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?

  • 1

    Has some specific language?

  • 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").

1 answer

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:

One should break into a?

Other considerations:

We still have the do ... while, that can be seen here:

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

And in Lua we also have the repeat:

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

  • 1

    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}

  • 1

    @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

You are not signed in. Login or sign up in order to post.