Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
3. do while loop
1 2
Example 1
Example 1
Expected Output
for (int x = 1; x <= 5; x++) //outer for - row XXXXXXXXXX
{
XXXXXXXXXX
for (int y = 1; y <= 10; y++) //inner for - column
cout << "X";
XXXXXXXXXX
cout << '\n'; XXXXXXXXXX
} XXXXXXXXXX
3 4
for (int x = 1; x <= 5; x++) is the In Example 1, for the first iteration of the
outer for loop, the inner for loop goes
outer for loop through all ten of its iterations, printing ten
for (int y = 1; y <= 10; y++) is the X characters and one new line character.
inner for loop Then, for the next iteration of the outer for
loop, the inner for loop again goes through
With nested for loops, for each all ten of its iterations, again printing ten X
iteration of the outer for loop, the characters and one new line character.
inner for loop goes through all its The same thing happens on the third, fourth,
iterations and fifth iterations of the outer for loop,
5
resulting in five rows of ten X characters. 6
Example 2
7 8
Example 2 Expected
Output
Each iteration of the outer x loop prints one
row of the multiplication table
1 2 3 4 5 On the first iteration, when x=1, the inner y
2 4 6 8 10 loop iterates 5 times, printing 1*y for each
value of y from 1 to 5
3 6 9 12 15
On the second iteration of the outer x loop
4 8 12 16 20 when x=2, the inner y loop iterates 5 times
5 10 15 20 25 again, this time printing 2*y for each value
of y from 1 to 5
9 10
Example 3
Note that the separate cout<<endl; The following program prompts the user for
statement must be inside the outer loop and the total number of salespersons as well as
outside the inner loop in order to produce the number of sales per salespersons
exactly one line for each iteration of the the user input each sale of each salesperson,
outer loop and then afterward displays the average
setw is used to set the width of the output sale for each salesperson.
field for each integer printed The number of iterations of the outer for
This aligns the outputs into a readable table loop will be the number of salespersons.
of 5 columns of right-justified integers The number of iterations of the inner for
loop will be the number of sales per
11 salesperson. 12
Example 3 Expected
Output
Enter number of salespersons: 2
Enter number of sales per salesperson: 3
Enter sale 1 for salesperson 1: 4
Enter sale 2 for salesperson 1: 5
Enter sale 3 for salesperson 1: 7
Average sales for salesperson #1 is 5.33333
Enter sale 1 for salesperson 2: 8
Enter sale 2 for salesperson 2: 3
Enter sale 3 for salesperson 2: 4
Average sales for salesperson #2 is 5
13 14
15 16
The while loop is similar to a for loop The parentheses following the for
in that both have the typical keyword consists of three expressions,
characteristics of a loop: the code initialization, condition, and update
inside each continues to iterate until a By contrast, the parentheses following
condition becomes false the while keyword consists only of the
The difference between them is in the condition; you have to take care of
parentheses following the for and any initialization and update elsewhere
while keywords in the code.
17 18
int num = 1;
while (num <= 10)
{
cout << num << " ";
num++;
}
19 20
21 22
num could also be updated inside the Updating the counter within the condition
parentheses following the while keyword requires two change
The update may possibly be done within the First, the value of num has to be initialized
condition itself to 0 instead of to 1 because the increment
inside the parentheses during the first
int num = 0; iteration of the loop would change that
variable’s value to 1.
while (num++ < 10)
cout << num << " ";
23 24
while (num++ < 10)
Second, the relational operator in the condition is The update of the variable is particularly
< rather than <= because the value of num is
being incremented before it is outputted. important with the while loop
Updating the counter within the condition raises the Without that update, the loop would be
question: Given the condition num++ < 10, which
comes first, the comparison or the increment? infinite
Since the increment is postfix, the answer is the
comparison
The counter also could be updated within the Example 7:
condition using a prefix increment.
int num = 1;
However, then the condition should be
++num<=10 to obtain the desired output. while (num <= 10)
25 cout << num << " "; 26
Example 7 Wrong
Using curly braces
Expected Output
111111111 If more than one statement belongs to
1 ………………………….. the while loop, then the statements
must be contained within curly braces.
That is why in the program that
outputs the numbers between 1 and
10 using the while loop, the two
statements in the body of the while
loop are contained within curly braces.
27 28
Example 8 Wrong
Expected Output
As with the for loop, the statement or Example 8:
statements following the while keyword and
parentheses will not execute if the int num=0
parentheses is followed by a semicolon, as while (num++ < 10);
that would be interpreted as an empty //Do not put semicolon after parentheses
statement cout << num << " ";
//Output
11
29 30
Example 9
Using the break Keyword
Expected output:
/*output
Enter a positive number: 0
Even though the while loop is a better
Number must be positive; please retry: -1 choice than a for loop for this program,
Number must be positive; please retry: 3 which requires the user to enter a
The number you entered is 3
*/
positive number, there are two
problems with this program:
• This program would be more difficult to – one minor
write with a for loop.
– one major
• While it could be done, the for loop is
designed for situations in which the number
of iterations is predictable. 35 36
The minor problem is that there is some The major problem is that the user is
repetition of code trapped inside the loop until they enter a
the user is requested both before and inside positive number.
the loop to enter a positive number. That is not a good programming design
A do while loop, which is explained later, While the user should be required to enter
avoids this repetition, but repeats other good data if they are going to enter any
code (there are tradeoffs in loops as well as data at all, they should have the option,
in life). when told the data entered was not valid, of
quitting the data entry.
37 38
int num;
cout << "Enter a positive number: ";
Example 10: cin >> num;
41 42
Using Flags
The flags modification is an improvement Ideally, we would only want to output the
because the user no longer is trapped inside data if it were valid.
the loop until they enter a positive number,
but instead has the option of quitting data If the data were not valid, then we would
entry. want to output that fact instead.
However, the second sample input and However, the code thus far does not enable
output, in which the user quits data entry,
illustrates a problem. us to differentiate whether the while loop
The final cout statement outputs the ended because the user entered valid data
number entered, even if the number is or because the user decided to quit after
invalid data. entering invalid data.
43 44
Expected output
45 46
Here is some sample input and output when the This program modification, in addition to
user does not enter a positive number but instead
decides to quit. This time the final output is not of using the logical && operator, uses a
the number entered, but rather that the user did Boolean variable named quit.
not enter a positive number: This Boolean variable is used as a flag.
Enter a positive number: 0 A flag is a Boolean variable whose value
Number must be positive; try again (Y/N): Y indicates whether a condition exists.
Enter number: -1 In this program, the while loop continues to
Number must be positive; try again (Y/N): N loop as long as the data entered is invalid
You did not enter a positive number and the user wants to keep going.
47 48
while (num<=0 && quit == false)
The first condition is if num <= 0 However, if num <= 0 is true, then the
If this expression is false, the data is valid, data is invalid, and the second condition,
so the issue of whether the user wants to whether quit is true, is evaluated.
quit does not arise.
Accordingly, the second condition, whether The value of quit may be true under either
quit is true, is not even evaluated. of two possibilities.
The while loop ends with the value of quit The first possibility is that this is the user’s
being false, its initialized value, and code first attempt to enter data and the data was
execution continues with the if / else
statement following the while loop. invalid.
49 50
In this case, the user has not yet been The second possibility is that this is
asked whether they want to quit. the user’s second or later attempt to
It is assumed they don’t, so they have enter data and the data was invalid.
the opportunity to answer whether In this case, the user has already been
they want to retry.
asked whether they want to quit, so
Therefore, the quit variable is the value of quit is based on the user’s
initialized to the value of false when it
is declared. answer.
51 52
If the value of quit is false, the while loop At some point (hopefully) the while
continues. loop will end, either because
However, if the user wants to quit, then the – the user has entered a valid number
right expression quit == false will be false
– or has not and decided to quit trying
because the value of quit is true.
Therefore, the while loop ends with the Code execution then continues with
value of quit being true, and code execution the if / else statement following the
continues with the if / else statement while loop.
following the while loop.
53 54
The value of quit being false Accordingly, we use the value of quit in the
if /else statement after the while loop to
necessarily indicates that the user differentiate whether the while loop ended
entered valid data, because if they – because the user entered valid data or
– instead decided to quit after entering invalid
were still trying to do so, the loop data.
would not have ended. Thus, inside the while loop, quit is a flag
whose value indicates whether the user
Conversely, the value of quit being wants to try again, and after the while loop
true necessarily indicates that the user ends, quit is a flag whose value indicates
entered invalid data. whether the user entered valid data.
55 56
While(true) – infinite loop
57 58
59