Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Do/While Loop | Loops
Introduction to C++

book
Do/While Loop

As an alternative to while loop you can use do/while loop. The difference is that the do/while loop will execute the code in the block once before checking if the condition returns true.

Syntax:

python
do {
// The code block
} while (condition);

The example of using do/while loop:

int i = 0;
do {
cout << i << endl;
i++;
} while (i < 3);
12345
int i = 0; do { cout << i << endl; i++; } while (i < 3);
copy

The first iteration will be firstly executed and i becomes 1. By the third iteration, i becomes 3 and the condition returns false after that, and do/while loop stops.

Pay attention, that the first iteration will be executed even if the condition is always false:

int i = 0;
do {
cout << i << endl;
i++;
} while (i < 0);
12345
int i = 0; do { cout << i << endl; i++; } while (i < 0);
copy
question-icon

Monica, Joey, and Janice put their money in the bank at 10% annual income. Fill the gaps in the program that accepts a user’s input the money of each person and calculate the annual income by multiplying the sum of money by 0.1 (10%).

#include
using namespace std;

int main() {
    // Create variable
    int i = 0;
    int amountOfMoney;

    // Use do/while loop to calculate the income
    
_ _ _
{
        cout << "Print the amount of money to put: ";
        
_ _ _
>> amountOfMoney;
        cout << "The annual income = " << amountOfMoney * 0.1 << endl;
        
_ _ _
;
    }
_ _ _
(i < 3);

    return 0;
}

Click or drag`n`drop items and fill in the blanks

dots
i++
dots
i--
dots
do
dots
switch
dots
cout
dots
while
dots
cin

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 4. Capitolo 2
some-alt