peaberry
peaberry

Reputation: 57

do-while loop into for loop

I made a game but didn't wanted to use do-while loops. So instead I tried to use for loops. The problem is when I run with do-while it works but when I run with for loops it doesn't work in the same way.

I think I changed do-while into for loops correctly. Can someone let me know what I am missing?

    do {
        crntShowBottle = rand() % 2 + 2;
    } while (crntShowBottle == prevShowBottle);
    prevShowBottle = crntShowBottle;



    for (;;) 
    {
        crntShowBottle = rand() % 2 + 2;
        if (crntShowBottle == prevShowBottle)
                break;
    } 
    prevShowBottle = crntShowBottle;

Upvotes: 1

Views: 151

Answers (1)

mostafiz67
mostafiz67

Reputation: 169

First, try to understand the mechanism of loop and how they are different from do-while loop and for loop.

Based on your code, what is happening!

  1. In the do-while section, you are giving instructions that "first do something" and then checking the condition. If the condition (checking) is true crntShowBottle == prevShowBottle then the loop must run again. Otherwise, if the condition is false crntShowBottle != prevShowBottle the loop must terminate.

  2. In the for loop section, you used the infinite loop for(;;). Means loop will be running infinite times. But, inside the loop you wrote the break condition. So, when the condition is matching crntShowBottle == prevShowBottle your loop is shutting down. So, you must use crntShowBottle != prevShowBottle

  3. You also need to understand, how break works!

Upvotes: 2

Related Questions