I am new to c++ and have a question about the while loop.

If I have one key condition that is let's say a gamebreaker. Ie money = less than 0, does everything else then go in a big while loopn which may contain many more while loops and if else statements.

Sorry if it seems a noobish question.

Recommended Answers

All 5 Replies

If I have one key condition that is let's say a gamebreaker. Ie money = less than 0, does everything else then go in a big while loopn which may contain many more while loops and if else statements.

Yes

plz clear ur question
u r telling a flow
whats the question?

plz clear ur question
u r telling a flow
whats the question?

Was just wondering if let's say a basic game letting you buy and sell things would be in a big while loop.

For example the loop basically says if your money is less than zero then it executes the code that's in the loop. Like buying more things or selling stuff untill you run out of money. When the while expression sees you have run out of money may print end of game and quit.

try somethng like this

while(money !=0){
   //do shopping
}

Hi BubblesBrian,

Programming is a very precise activity. Whether you understand while() loops or not, you will likely find it a frustrating process until you learn to express what you're trying to do clearly and precisely. On the flip side, once you can do that, you'll likely find that the code almost writes itself!

Maybe a construct like the following would prove useful?

bool quit = false;
while (! quit) {
    bool allowBuying = true;
    if (money <= 0.0)
        allowBuying = false;
    if (allowBuying) {
        cout >> "Would you like to buy or sell (B/S)?";
        ...
    }
    else {
        cout << "You are out of money.  Would you like to sell (Y/N)?" 
        // if no, set quit = true;
    }

    if (quit)
        continue;  // go back to top and then exit loop, or "break" to exit now
    
    // do other stuff
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.