Professional Documents
Culture Documents
: Zulaile Mabni
: CSC425 Introduction To Computer Programming
Objectives
In this chapter you will:
Learn about repetition (looping) control
structures
Explore how to construct and use countcontrolled, and sentinel-controlled repetition
structures
Discover how to form and use nested control
structures
10
Sample Program
// Find the total of numbers using counter-controlled while loop
11
Sample Program
// Find the maximum number using counter-controlled while loop
12
13
Sample Program
// Find the total and average of numbers using sentinel-controlled while loop
14
15
statement
while (expression);
21
22
26
27
28
29
Answer:
*****
****
***
**
*
C++ Programming: From Problem Analysis to Program Design, Third Edition
30
Summary
C++ has three looping (repetition) structures:
while, for, and dowhile
while, for, and do are reserved words
while and for loops are called pre-test
loops
do...while loop is called a post-test loop
while and for may not execute at all, but
do...while always executes at least once
C++ Programming: From Problem Analysis to Program Design, Third Edition
31
Summary (continued)
while: expression is the decision maker, and
the statement is the body of the loop
In a counter-controlled while loop,
Initialize counter before loop
Body must contain a statement that changes the value
of the counter variable
32
EXERCISE
1) What is the output of the following code?
a) num = 5;
while (num > 9)
num = num + 2;
num = num + * 10;
cout << num << endl;
b)
num = 5;
while (num > 9)
{
num = num + 2;
num = num + * 10;
}
cout << num << endl;
33
EXERCISE
2) Suppose the input is 38 45 71 4 -1. What is the output of
the following code?
34
EXERCISE
3) What is the output when the code executes? How many
times do the loop executes?
x = 5; y = 50;
do
x = x + 10;
while ( x < y);
cout<<x<< <<y<<endl;
35
EXERCISE
4) What is the output when the code executes?
36