Sei sulla pagina 1di 8

Chapter 4(b) –

Nesting for Loops


Repetition (While Loop)
 Iteration / loop  Similar to the if statements, the for loop
could also be nested
 There are 3 types of repetition  Syntax
structure:
1. for loop
for ( initialization ; condition ; update )
for ( initialization ; condition ; update )
- nested for loop statement;
2. while loop

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

 As an illustration, in a clock, minutes // prints a 5x5 multiplication table:


are the outer loop, seconds the inner
loop. for (int x=1; x <= 5; x++)
{
 In an hour, there are 60 iterations of
for (int y=1; y <= 5; y++)
minutes, but for each iteration of a
cout << setw(4) << x*y;
minute, there are 60 iterations of cout << endl;
seconds. }

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

The while Loop


 For example, in a data entry application, you may
 The for loop generally is used when want a loop that, upon entry of invalid data, asks
the loop will execute a fixed number of the user whether they want to retry or quit, and if
they want to retry, gives the user another
times. opportunity to enter data.
 The number of times this loop may execute is
 However, sometimes the number of unpredictable, since it will keep repeating until the
times a loop will execute is user either enters valid data or quits.
 This chapter will show you how to use the while
unpredictable, depending on user loop, which is a better choice than a for loop when
input during runtime the number of times a loop will iterate is
unpredictable.

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

Comparison of for and


while Loops - 1
 Example 4: Using for loop
 A comparison is made between the
for loop and the while loop using two for (int num = 1; num <= 10; num++)
cout << num << " ";
programs that both outputs the
numbers between 1 and 10  Example 5: Using while loop

int num = 1;
while (num <= 10)
{
cout << num << " ";
num++;
}
19 20

Example 4 and Example 5


Expected Output
 1 2 3 4 5 6 7 8 9 10  With the while loop, the integer variable
num had to be declared and initialized
before the loop since this cannot be done
inside the parentheses following the while
keyword
 num was updated inside the code of the
loop using the increment operator

21 22

Example 6 int num = 0;

 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

Comparison of for and


while Loops - 2
 The only number that would output is  The practical difference between the for and
while loops is not apparent in a program
11. with a predictable number of iterations,
 The reason is that the loop continues, such as the program we have been
discussing thus far that outputs the
and the empty statement executes, numbers between 1 and 10.
until the condition fails when num is  Rather, a while loop is a superior choice to a
for loop in a program where the number of
11, at which time the statement iterations is unpredictable, depending on
following the loop executes and the user input during runtime.
value ’11’ is outputted
31 32
Example 9
 In the following program, the program asks int num;
cout << "Enter a positive number: ";
the user to enter a positive number, and in
cin >> num;
a loop continues that request until the user
does so. while (num <= 0)
 The number of times this loop may execute {
is unpredictable. cout << "Number must be positive; please retry: ";
cin >> num;
 It may never execute if the user enters a }
positive number the first time, cout << "The number you entered is " << num << " ";
 or it may execute many times if it takes the
user several tries to enter a positive number.
33 34

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;

while (num <= 0)


{
 The following modification of the cout << "Number must be positive; try again (Y/N): ";
cin >> choice;
program uses the break keyword to
provide the user with the option of //continue to get a number if user want to try again
quitting the data entry: if (choice == 'Y')
{
cout << "Enter number: ";
cin >> num;
}
else
break; //break out from loop if user want to quit
}
39 cout << "The number you entered is " << num << " "; 40
Example 10
Expected Output
 Here is some sample input and output when  Here is some sample input and output when
the user eventually enters a positive number: the user does not enter a positive number
but instead decides to quit:
Enter a positive number: 0
Number must be positive; try again (Y/N): Y
Enter number: -1 Enter a positive number: -2
Number must be positive; try again (Y/N): Y Number must be positive; try again (Y/N): N
Enter number: 3 The number you entered is -2
The number you entered is 3

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

 Here is some sample input and output when


the user eventually enters a positive number:

Enter a positive number: -3


Number must be positive; try again (Y/N): Y
Enter number: 3
The number you entered is 3

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

 Programmers sometimes make the condition


of the while loop always true, such as while
(true) or while (1), and break out of the
while loop with the break keyword.
 Here is an example that is a modification of
the program we have been using that asks
the user to enter a positive number.

57 58

 The one advantage of this modification is that it


renders unnecessary having to prompt the user
both before and inside the loop to enter a positive
number.
 However, the use of the while (true) syntax has the
disadvantage of making your code less readable
 because the condition that stops the loop cannot be
regconized from the parentheses following the
while keyword.
 The do while loop avoids this disadvantage and
would be a preferable choice.

59

Potrebbero piacerti anche