C - Programming - C - Program - Chapter 05.pdf
(
867 KB
)
Pobierz
CHAPTER
5
C
ONTROL
S
TRUCTURES
II
(R
EPETITION
)
IN THIS CHAPTER, YOU WILL:
n
Learn about repetition (looping) control structures
n
Explore how to construct and use counter-controlled,
sentinel-controlled, flag-controlled, and EOF-controlled
repetition structures
n
Examine
break
and
continue
statements
n
Discover how to form and use nested control structures
232
|
Chapter 5: Control Structures II (Repetition)
In Chapter 4, you saw how decisions are incorporated in programs. In this chapter, you
learn how repetitions are incorporated in programs.
Why Is Repetition Needed?
Suppose you want to add five numbers to find their average. From what you have learned
so far, you could proceed as follows (assume that all variables are properly declared):
cin >> num1 >> num2 >> num3 >> num4 >> num5;
//read five numbers
sum = num1 + num2 + num3 + num4 + num5;
//add the numbers
average = sum / 5;
//find the average
But suppose you want to add and average 100, or 1000, or more numbers. You would
have to declare that many variables, and list them again in
cin
statements and, perhaps,
again in the output statements. This takes an exorbitant amount of space and time. Also, if
you want to run this program again with different values, or with a different number of
values, you have to rewrite the program.
Suppose you want to add the following numbers:
5 3 7 9 4
Consider the following statements, in which
sum
and
num
are variables of type
int
:
1.
sum = 0;
2.
cin >> num;
3.
sum = sum + num;
The first statement initializes
sum
to
0
. Let us execute statements 2 and 3. Statement 2
stores
5
in
num
; statement 3 updates the value of
sum
by adding
num
to it. After statement
3, the value of
sum
is
5
.
Let us repeat statements 2 and 3. After statement 2 (after the programming code reads the
next number):
num = 3
After statement 3:
sum = sum + num = 5 + 3 = 8
At this point,
sum
contains the sum of the first two numbers. Let us again repeat
statements 2 and 3 (third time). After statement 2 (after the code reads the next number):
num = 7
After statement 3:
sum = sum + num = 8 + 7 = 15
Now
sum
contains the sum of the first three numbers. If you repeat statements 2 and 3
two more times,
sum
will contain the sum of all five numbers.
while
Looping (Repetition) Structure
|
233
Ifyouwanttoadd10numbers,youcanrepeatstatements2and3tentimes.Andifyouwantto
add 100 numbers, you can repeat statements 2 and 3 one hundred times. In either case, you do not
have to declare any additional variables, as you did in the first code. You can use this C++ code to
add any set of numbers, whereas the earlier code requires you to drastically change the code.
There are many other situations where it is necessary to repeat a set of statements. For
example, for each student in a class, the formula for determining the course grade is the same.
C++ has three repetition, or looping, structures that let you repeat statements over and over
until certain conditions are met. This chapter introduces all three looping (repetition)
structures. The next section discusses the first repetition structure, called the
while
loop.
while
Looping (Repetition) Structure
In the previous section, you saw that sometimes it is necessary to repeat a set of statements
several times. One way to repeat a set of statements is to type the set of statements in the
program over and over. For example, if you want to repeat a set of statements 100 times,
you type the set of statements 100 times in the program. However, this solution of
repeating a set of statements is impractical, if not impossible. Fortunately, there is a better
way to repeat a set of statements. As noted earlier, C++ has three repetition, or looping,
structures that allow you to repeat a set of statements until certain conditions are met.
This section discusses the first looping structure, called a
while
loop.
5
The general form of the
while
statement is:
while
(expression)
statement
In C++,
while
is a reserved word. Of course, the
statement
can be either a simple
or compound statement. The
expression
acts as a decision maker and is usually a
logical expression. The
statement
is called the body of the loop. Note that the
parentheses around the
expression
are part of the syntax. Figure 5-1 shows the flow
of execution of a
while
loop.
expression
true
statement
false
FIGURE 5-1
while
loop
234
|
Chapter 5: Control Structures II (Repetition)
The
expression
provides an entry condition. If it initially evaluates to
true
,the
statement
executes. The loop condition—the
expression
—is then reevaluated. If it again
evaluates to
true
,the
statement
executes again. The
statement
(body of the loop)
continues to execute until the
expression
is no longer
true
. A loop that continues to
execute endlessly is called an infinite loop. To avoid an infinite loop, make sure that the loop’s
body contains statement(s) that assure that the exit condition—the expression in the
while
statement—will eventually be
false
.
EXAMPLE 5-1
Consider the following C++ program segment:
i = 0;
//Line 1
while
(i <= 20)
//Line 2
{
cout << i << " ";
//Line 3
i = i + 5;
//Line 4
}
cout << endl;
Sample Run:
0 5 10 15 20
In Line 1, the variable
i
is set to
0
. The
expression
in the
while
statement (in Line
2),
i
<
= 20
, is evaluated. Because the expression
i
<
= 20
evaluates to
true
, the body of
the
while
loop executes next. The body of the
while
loop consists of the statements in
Lines 3 and 4. The statement in Line 3 outputs the value of
i
, which is
0
. The statement
in Line 4 changes the value of
i
to
5
. After executing the statements in Lines 3 and 4, the
expression
in the
while
loop (Line 2) is evaluated again. Because
i
is
5
,the
expression
i
<
= 20
evaluates to
true
and the body of the
while
loop executes again.
This process of evaluating the
expression
and executing the body of the
while
loop
continues until the
expression
,
i
<
= 20
(in Line 2), no longer evaluates to
true
.
The variable
i
(in Line 2, Example 5-1 ) in the expression is called the loop control variable.
Note the following from Example 5-1:
a.
Within the loop
i
becomes
25
, but is not printed because the entry
condition is
false
.
b.
If you omit the statement:
i = i + 5;
from the body of the loop, you will have an infinite loop, continually
printing rows of zeros.
while
Looping (Repetition) Structure
|
235
c.
You must initialize the loop control variable
i
before you execute the
loop. If the statement:
i = 0;
(in Line 1) is omitted, the loop may not execute at all. (Recall that
variables in C++ are not automatically initialized.)
d.
In Example 5-1, if the two statements in the body of the loop are
interchanged, it may drastically alter the result. For example, consider
the following statements:
i = 0;
while
(i <= 20)
{
5
i = i + 5;
cout << i << " ";
}
cout << endl;
Here the output is
:
5 10 15 20 25
Typically, this would be a semantic error because you rarely want a
condition to be true for
i
<
= 20
, and yet produce results for
i
>
20
.
e.
If you put a semicolon at the end of the
while
loop, (after the logical
expression), then the action of the
while
loop is empty or null. For
example, the action of the following
while
loop is empty.
i = 0;
while
(i <= 20);
{
i = i + 5;
cout << i <<
" ";
}
cout << endl;
The statements within the braces do not form the body of the
while
loop.
Designing
while
loops
As in Example 5-1, the body of a
while
executes only when the
expression
,inthe
while
statement, evaluates to
true
. Typically, the
expression
checks whether a
variable(s), called the loop control variable (LCV), satisfies certain conditions. For
example, in Example 5-1, the
expression
in the
while
statement checks whether
i
<
= 20
. The LCV must be properly initialized before the
while
loop and it should
Plik z chomika:
Januszek66
Inne pliki z tego folderu:
Back Seat_ A Mumbai Tale - Aditya Kripalani.mobi
(755 KB)
Brief Wondrous Life of Oscar Wao, The - Junot Diaz.opf
(3 KB)
Don't Make Me Think, Revisited_ - Steve Krug.mobi
(9256 KB)
M. T. Anderson - Norumbegan 03 - The Empire of Gut and Bone # (v5.0).epub
(2209 KB)
M. T. Anderson - Norumbegan 02 - The Suburb Beyond the Stars # (v5.0).epub
(2105 KB)
Inne foldery tego chomika:
Dokumenty
Galeria
LUDLUM ROBERT
Midi - Kar
Mszał Rzymski PL
Zgłoś jeśli
naruszono regulamin