Sie sind auf Seite 1von 15

Lesson 5: Looping (While and Do...

While)
Slide 1: Lesson Outline
This document is designed to help you take notes while watching the videos for this
lesson. Print these slides before going to the Video Lectures.
Note: Reviewing this material is not sufficient to fully understand the topic; you should
also complete the readings and exercises.
Review these slides

While (slides 2-19)


Do...While (slides 20-30)

Slide 2: While
Quick Review:
Types of Statements Seen to Date
1. Declaration statement
Ex:
2. Declaration/Initialization statement
Ex:
3. Input/Output statement
Ex:
4. Assignment statement
Ex:
5. Selection statement
Ex:

Lesson 5

Slide 3:
3 While
Shamp
poo Algor
rithm:
Version 1
What is
s wrong with
w
this allgorithm?

Wet
Hair
Pour
Lather
Rinse
Repeat
Dry Hairr

Lesson 5

Slide 4:
4 While
Shamp
poo Algor
rithm: Ve
ersion 2

Better
but whatt is wrong
g with this
s algorithm
m?
Wet Hair

while Ha
air is dirty
Pour Sha
ampoo
Lather
Rinse
Dry Hairr

Slide 5:
5 While
Shamp
poo Algor
rithm:
Version 3
_________________
Wet Hair
while (H
Hair is dirty and _ _ _ _ _ _ _ _ _))
Pour Sha
ampoo
Lather
Rinse
__________=______________
Dry Hairr
Check video for ansswer.
Lesson 5

6: While
While Loop
p

ogical expre
ession) // lo
oop test
ody>
nt
le 1:
(n <= 3)
ut << "te
est " << n << end
dl;
= n + 1;
< "So lo
ong";

7: While
While Loop
p (cont'd)
At the starrt of each lo
oop iteratio
on, the logiical expresssion (condition) is
ed.

8: While
While Loop
p (cont'd)
If the cond
dition is tru
ue, the code in the loo
oop body iss executed aand program
automaticallly returns to
t the loop
p test (cond
dition) to e
evaluate the
e logical
on.

9: While
While Loop
p (cont'd)
If the cond
dition is fallse, the loo
op process tterminates and progra
am control
to the next statement that is the first state
ement afte
er the loop
p.

10: While
e
While Loop
p (cont'd)
ulary
ment includ
des a logica
al expressio
on, called th
he loop tesst, that tessts whether the
should conttinue and a loop body
y that defin
nes a task tthat is repe
eated.
execution of
o the task is called an
n iteration
n of the loop.
of one or more
m
loop control ob
bjects are used to determine the
e number o
of
tions.
value of the
e control ob
bjects is upd
dated in thee loop bodyy.
ile loop can
n be executted 0, 1 or many
m
timess.

Slide 11:
1 While
e
The wh
hile Loop
p (cont'd)
)
Examplle 2:
A while loop assign
ns a PASS/F
FAIL grade to
t four stud
dents. A sco
ore of at le
east 70 is
required
d for a passs.

studen
ntNo = 1;
while (student
tNo <= 4)
{
// in the lo
oop body, read a score an
nd give a grade
cin >> score
e;
= 70)
if (score >=
cout
c
<< "PASS" <<
< endl;
else
cout
c
<< "FAIL" <<
< endl;
// update
u
th
he value of stude
entNo
stud
dentNo++;
}

Slide 12:
1 While
e
The While
W
Loop
p (cont'd)
A countter-contro
olled loop performs a fixed numb
ber of itera
ations.

The lo
oop test de
etermines when
w
the loo
op has finisshed executting.

The number
n
of iterations iss determine
ed before beeginning th
he loop.

Lesson 5

Slide 13: While


The While Loop (cont'd)
An event-controlled loop performs an indefinite number of iterations.

The loop test looks at an event condition that specifies when the loop should
terminate.

The number of iterations depends on run-time conditions in the program.

The two examples seen to date are counter-controlled loops.

Slide 14: While


Event-Controlled While Loop
Example 3:
What does this code segment do?
How many times will the loop be executed?
cout << " (Y)es or (N)o?";
cin >> ans;
valid = ans == 'Y' || ans == 'N';
while (!valid)
{
cout << "That is not a valid response." <<endl;
cout << "Try again : (Y)es or (N)o?";
cin >> ans;
valid = ans == 'Y' || ans =='N';
}
Check video for answer.

Lesson 5

Slide 15: While


Event-Controlled While Loop (cont'd)
Example 4:
How many times will this loop execute?
sum = 0;
while (sum <= 21)
{
cout << "Enter a # between 1 and 5: ";
cin >> num;
sum += num;
}
cout << "Over 21!!!\n"
<< "Last number entered is " << num;

Slide 16: While


More Examples
Example 5:
What will the following code fragment output?
n = 0;
sum = 0;
while (n != 11)
{
n += 2;
sum += n;
}
cout << "sum = " << sum << endl;

Lesson 5

17: While
e
Examples
s (cont'd)
)
le 6:
ill the follow
wing code fragment
f
ou
utput?
(a > 0)
m = 5;
ut << num
m <<endl;
< "Value
e of a is
s" << a;

18: While
e
Examples
s (cont'd)
)
le 7:
he code and
d identify th
he output. Assuming
A
ut is 2aZ?zv
v

representss the new line charactter,

t(c);
(c!= '\n
n' )
c == 'Z' || c ==
= 'z')
c = '*';
if (c >=
> 'A' &&
& c < 'Z' || c >=
= 'a' && c < 'z')
)
c++;
<< c;
get(c);

10
0

Slide 19: While


You Try
Create loops that implement each of the following algorithms.
a) With a while loop, add the even integers between 2 and 20 and print the sum.
b) The while loop begins with n = 10 and prints the square of 10, 8, , 2.
c) A school band sets out to collect $5000. Write a sequence of statements that reads
the individual contribution and outputs the cumulative sum to that point. Continue until
the $5000 is raised. Print the total amount of money collected and the amount of the
largest contribution.
Check video for answers.

Slide 20: Do...While

The do/while statement places the loop test at the end of the loop body.

It is called a POST-TEST loop.

Form:
do
<loop body>
while (logical expression) ; // loop test

Slide 21: Do...While


Example 1:
A user must enter the password "SYSTEM" to gain access to the main server. A
do/while loop allows for repeated attempts to log in until the correct password is
entered.
string password;
do
{
cout << "Enter the password: ";
cin >> password;
}
while (password != "SYSTEM"); // test the password

Lesson 5

11

22: Do...W
While
Do...While vs. W
While
POST-TES
ST loop (exiit-condition); PRE-TE
EST loop (e
entry-condittion);
The loopin
ng condition
n is tested
after execcuting the lo
oop body;

The loo
oping condiition is teste
ed
before executing tthe loop bo
ody;

The loop body


b
is always execute
ed The loo
op body ma
ay not be
at least on
nce.
executeed at all.

23: Do...W
While
he expressio
on is tested
d and found
d to be falsee, the loop is exited and control
to the state
ement that follows
f
the do-while sttatement.

12
2

Slide 24: Do...While


Example 1: Asking the User if S/he Wants to Continue?
//Find sum of any number of inputs.
int sum =0, num;
char ans;
do
{
cout << "Enter number : ";
cin >> num;
sum += num;
cout << "Continue (n/any key to continue)?";
cin >> ans;
}
while (ans != 'n' && ans != 'N');
cout << "Sum = " << sum << endl;

Slide 25: Do...While


Exercise 1
What will be output by each of the following code fragments?
a)
n = 1;
while (n <= 9)
{
n = n + 5;
cout << n << endl;
}
b)
n = 1;
while (n <= 9)
{
cout << n << endl;
n = n + 5;
}
Check video for answers.

Lesson 5

13

Slide 26: Do...While


Exercise 1 (cont'd)
What will be output by each of the following code fragments?
c)
n = 1;
while (n <= 9)
cout << n << endl;
n = n + 5;
d)
n = 1;
while (n > 9)
{
n = n + 5;
cout << n << endl;
}

Slide 27: Do...While


Exercise 1 (cont'd)
What will be output by each of the following code fragments?
e)
n = 1;
do
{
n = n + 5;
cout << n << endl;
}
while (n > 9);

Lesson 5

14

Slide 28: Do...While


Exercise 2
What will be output by each of the following code fragments if the user enters 3?
a)
cout << "How many Hellos?";
cin >> howMany;
do
{
cout << "Hello";
howMany -= 1;
} while (howMany > 0);

Slide 29: Do...While


Exercise 2 (cont'd)
What will be output by each of the following code fragments if the user enters 3?
b)
cout << " How many Hellos? "
cin >> howMany;
while (howMany > 0)
{
cout << "Hello ";
howMany -= 1;
}

Slide 30: Do...While


Exercise 3
Write a program that uses a sentinel loop to input several positive integers (> 0). The
program will then output the number of inputs, the smallest and largest input, and the
sum and mean of the inputs.
1) Develop algorithm using pseudocode/flowchart.
2) Write the program.

Lesson 5

15

Das könnte Ihnen auch gefallen