简体   繁体   中英

C++ Nested Loops

I've been having a lot of trouble trying to code this nested loop.

We have to count bubbles and their respective baubles.

I must prompt the user to input an integer for the number of bubbles. And prompt the user to input an integer for the number of baubles per bubble.

Each bubble will say BLOP! After each bubble, each of its baubles will say "bloop!" all in a row, followed by a new line.

my code is:

cout << "How many bubbles are there? ";
cin >> bubbles;
cout << "How many baubles are being created by each bubble? ";
cin >> baubles;


while (bubbles > 0) {
    cout << "BLOP!" << endl;
    bubbles--;
    for (baubles; baubles > 0; baubles--) {
        cout << "bloop!" << endl;
    }
}

The problem is I can't get the 'bloops!' to appear the correct number of times after the first loop iteration. This is likely because I am decrementing the baubles to 0; but I have to do this in order to get out of the inner loop each time and for the inner loop to print the correct number of baubles.

For a sample input of 4 bubbles and 2 baubles; My output is :

BLOP!
bloop!
bloop!
BLOP!
BLOP!
BLOP!

and it should be

BLOP!
bloop!
bloop!
BLOP!
bloop!
bloop!
BLOP!
bloop!
bloop!
BLOP!
bloop!
bloop!

Any help is appreciated. I've tried numerous loop methods and included if statements to try to get this to work but I just can't seem to get it.

 for (baubles; baubles > 0; baubles--) 

Should be:

 for (baubles2 = baubles; baubles2 > 0; baubles2--) 

Because it has to reset every time. It would stay 0 forever after the first iteration otherwise.

You need to reset the variable baubles to its original value every time you iterate over bubbles , use another variable baubles0 :

cout << "How many bubbles are there? ";
cin >> bubbles;
cout << "How many baubles are being created by each bubble? ";
cin >> baubles0;


while (bubbles > 0) {
cout << "BLOP!" << endl;
bubbles--;
for (baubles = baubles0; baubles > 0; baubles--) {
    cout << "bloop!" << endl;

}
}
cout << "How many bubbles are there? ";
cin >> bubbles;
cout << "How many baubles are being created by each bubble? ";
cin >> baubles;


while (bubbles > 0) {
cout << "BLOP!" << endl;
bubbles--;
for (int baubles_aux = baubles; baubles_aux > 0; baubles_aux--) {
        cout << "bloop!" << endl;

}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM