Transcript while
Chapter 5 Loops
§5.1 The “while” Loop
§5.2 The “do-while” Loop
§5.3 The “for” Loop
§5.4 Nested loop
§5.5 “break” and “continue”
Motivations
Question: please write a program to print a string
(e.g., "Welcome to C++!") ten times.
-- Easy!
cout
cout
cout
cout
cout
<< "Welcome to C++!" << endl;
<< "Welcome to C++!" << endl;
<< "Welcome to C++!" << endl;
<< "Welcome to C++!" << endl;
<< "Welcome to C++!" << endl;
--How about 1000 times?
2
§4.1 The “while” Loop
while (loop-continuation-condition)
{
// loop-body;
Statement(s);
}
3
int count = 0;
while (count < 100)
{
cout << "Welcome to C++!\n";
count++;
}
Trace while Loop
Print
“Welcome
to
C++”
Print
(count
(count
The
“Welcome
loop
<count
<count
2):
2):
exits.
to
true
Initialize
2)
count
:false
true
Increase
byC++”
Increase
by
11
Execute the next statement.
int count = 0;
while (count < 2)
{
count
cout << "Welcome to C++!";
count++;
}
Welcome to C++!
Welcome to C++!
4
0
2
1
Example: Multiple Subtraction Quiz
The Math subtraction tutor program in Listing 3.4,
SubtractionTutor.cpp, generates just one question for each run.
Listing 5.4 gives a program that generates ten questions and
reports the number of the correct answers after a student answers
all ten questions.
The program also displays the time spent on the test and lists all
the questions, as shown in sample output.
SubtractionQuizLoop
5
Example: Repeat Subtraction Quiz
In the previous subtraction quiz Listing 3.4 , each question can be
answered only once.
Listing 5.1 gives a program that let the user enter a new answer if
the previous answer is incorrect, and terminate until the correct
answer is entered.
RepeatSubstractionQuiz
6
Unknown # of Loop Executions
• How to terminate a loop, if
– The number of loop executions is not
predetermined?
• Two methods
– User confirmation, or
– Sentinel value
7
Controlling a Loop with User Confirmation
char continueLoop = 'Y';
while (continueLoop == 'Y')
{
// Execute body once
// Prompt the user for confirmation
cout << "Enter Y to continue and N to quit: ";
cin >> continueLoop;
}
8
Ending a Loop with a Sentinel Value
A program that reads and calculates the sum of an
unspecified number of integers.
The input 0 signifies the end of the input.
SentinelValue
9
Caution
Don’t use floating-point values for
equality checking in a loop control.
Since floating-point values are approximations.
double data = pow(sqrt(2.0), 2) - 2;
while (data != 0){
cout << “Data is not zero: "<<data<<endl;
data = pow(sqrt(data), 2) - data;
}
10
Example: Reading Data from a File
Listing 4.10 reads three numbers from the data file.
To read many numbers, you need a loop.
What to do if you don’t know the number of numbers
in the file?
-- terminate at the end of file!
-- How? Use the eof() function.
Listing 5.6 revises Listing 5.10 to read all numbers
from the file score.txt.
ReadAllData
11
Check Point
• Please analyze the following code.
• Is count<100 always true/false at Point A,
Point B, and Point C?
12
int count = 0;
while (count<100)
{
//Point A
cout<< "Welcome to C++!\n";
count++;
//Point B
}
//Point C
§5.2 The “do-while” Loop
“while”
“do-while”
Statement(s)
(loop body)
true
Loop
Continuation
Condition?
false
do{
// Loop body;
Statement(s);
13
} while (loop-continuation-condition);
Example
• Listing 5.7: a program that reads and
calculates the sum of an unspecified number
of integers.
– The input 0 signifies the end of the input.
TestDoWhile
14
Check Point
• How many times is the following loop body
repeated? What’s the printout?
15
int i = 1;
while (i<4){
if(i%2 == 0)
cout<<i<<endl;
i++;
}
int i = 1;
while (i>4){
if(i%2 == 0)
cout<<i<<endl;
i++;
}
int i = 1;
do{
if(i%2 == 0)
cout<<i<<endl;
i++;
}while (i<4);
int i = 1;
do{
if(i%2 == 0)
cout<<i<<endl;
i++;
}while (i>4);
§5.3 The “for” Loop
for (initial-action; loop-continuation-condition; action-after-each-iteration)
{
// loop body;
Statement(s);
}
int i;
for (i = 0; i < 100; i++)
{
cout << "Welcome !\n";
}
cout<<“Welcome!\n”;
16
Trace for Loop
int i;
for (i = 0; i < 2; i++)
{
cout << "Welcome to C++!";
}
Exit the loop.
Execute the next statement after the loop
17
PrintExecute
Welcome
tostatement:
Execute
Execute
Print
“Welcome
adjustment
adjustment
(i(i <<Declare
2):
2):initializer:
false
true
statement
C++!”
i C++!
i now
i:
ii::i:2101is0 2
Note
• All the three control expressions in “for” loop can be omitted
• But the semicolons can not be omitted
1) sum=0; i=1;
for (; i<=100; i++)
sum += i;
2) sum=0;
for (i=1; ; i++){
if (i>100) break;
sum += i;
}
3) sum=0;
for (i=1; i<=100; ){
sum += i;
i++;
}
18
4)
sum=0; i=1;
for (; i<=100;){
sum += i;
i++;
}
5)
sum=0; i=1;
for ( ; ; ){
if (i>100) break;
sum += i;
i++;
}
-- If the loop-continuation-condition in
a for loop is omitted, it is implicitly true.
-- It may result in infinite loop.
Note
• The initial-action and action-after-each-iteration can
be a list of comma-separated expressions
– rarely used in practice
for (int i = 0, j = 0; (i + j < 10); i++, j++) {
// Do something
}
“,” operator
19
The Operator “ , ”
• “ , ”:
– Concatenate expressions
– The result value: the value of the rightmost
expression
– Precedence: the lowest (lower than “=“)
20
int main(){
int x, y;
x=50;
for (int i = 0, j = 0; i + j < 10; i++, j++) {
y=(x=x-5, x/5);
cout<<x<<" "<<y<<endl;
}
}
Example: Using for Loops
Problem: Write a program that sums a series that starts
with 0.01 and ends with 1.0.
The numbers in the series will increment by 0.01, as
follows: 0.01 + 0.02 + 0.03 and so on.
TestSum
21
Floating-point Numbers in
Relational Expressions
int main(){
int main()
// Initialize sum
{double sum = 0;
// Initialize
sum
double
prei=0;
doublei; sum = 0;
double
The sum is 49.5
i is increased by 0.01
The final i is 1, and i-1.0 is
6.661338148e-016
double i=0;
// Add 0.01, 0.02, ..., 0.99, 1 to sum The sum is 50.5
for
0.01;
i i==0.99,
i i++0.01){
i is increased by 0.009999999776
for
(i(i == 0.01f;
<= 1.0;
1.0f;
0.01f){
// Add
0.01,ii <=
0.02,
...,
1 to sum
i; i <= 1.0; i = i + 0.01) The final i is 1.009999977, and i-1.0 is
forsum
(i = +=
0.01;
prei=i;+= i;
0.009999977425
sum
}
// Display result
// Display result
cout<<<<"The
"The
sum
<< sum;
cout
sum
is "is<<" sum<<endl;
return 0;
cout<<setprecision(10)<<"i
is increased by "<<i-prei<<endl;
cout<<"The final i is "<<i<<", and i-1.0 is " <<(i-1.0)<<endl;
}
return 0;
}
22
Which Loop to Use?
while, do-while, and for, are expressively equivalent
and mutually conversable.
while (loop-continuation-condition) {
// Loop body
}
Equivalent
(a)
for (initial-action;
loop-continuation-condition;
action-after-each-iteration) {
// Loop body;
}
(a)
for ( ; loop-continuation-condition; )
// Loop body
}
(b)
Equivalent
initial-action;
while (loop-continuation-condition) {
// Loop body;
action-after-each-iteration;
}
(b)
23
• “for”:
Which Loop to Use?
– if the number of repetitions is known.
• “while”:
– if the number of repetitions is unknown
• “do-while”:
– to replace a while loop if the loop body has to be
executed before testing the continuation condition.
24
Check Point
• Convert the following while loop into a for
loop.
int i =1;
int sum =0;
while (sum<10000)
{
sum +=i;
i++;
}
25
§5.4 Nested loop
• Loop with one outer loop and one or more
inner loops
26
Nested Loops
A program that uses nested for loops to print a
multiplication table.
TestMultiplicationTable
27
Case Study: Monte Carlo Simulation
The Monte Carlo simulation refers to a technique that uses random
numbers and probability to solve problems.
This method has a wide range of applications in computational
mathematics, physics, chemistry, and finance.
For example:
circleArea / squareArea = / 4.
y
1
≈ 4 * numberOfHits / 1000000.
-1
1
x
MonteCarloSimulation
-1
28
Case Study: Converting Decimals to
Hexadecimals
How do you convert a decimal number to a hexadecimal
number?
To convert a decimal number d to a hexadecimal number is to
find the hexadecimal digits hn, hn-1, hn-2, ... , h2, h1, and h0
such that
d hn 16n hn 1 16n 1 hn 2 16n 2 ... h2 162 h1 161 h0 160
These hexadecimal digits can be found by successively dividing d by 16
until the quotient is 0. The remainders are h0, h1, h2, ... , hn-2, hn-1, and hn.
Dec2Hex
29
§5.5 “break” and “continue”
• break:
– May only be used inside a loop or a switch statement.
– To terminate the current loop/switch immediately and
transfer control to the statement immediately following
that loop/switch.
30
sum=0; mark=1;
for ( i=0; ; ){
if (i>100) break;
sum += i;
i++;
}
if(i>0) avgnum = sum/I;
…
“continue”
• “continue”:
– May only be used inside a loop.
– To terminate the current iteration of the loop and
proceeds directly to the next.
• In the case of a for loop it jumps to its action-aftereach-iteration. sum=0; mark=1;
31
for ( i=0; ; ){
if (i>100) continue;
sum += i;
i++;
}
if(i>0) avgnum = sum/I;
…
Examples
Use of “break”
TestBreak
Use of “continue”
TestContinue
32
Case Study: Checking Palindrome
Problem: Write a program that tests whether a string is a
palindrome.
A string is a palindrome if it reads the same forward and
backward. The words “mom,” “dad,” and “noon,” for
example, are all palindromes.
How do you write a program to check whether a string is a
palindrome?
Solution: One solution is to check first-last, second-secondlast, …, the middle!
TestPalindrome
33
Loop Example:
Displaying Prime Numbers
Problem: Write a program that displays the first 50 prime numbers in
five lines, each of which contains 10 numbers.
An integer greater than 1 is prime if its only positive divisor is 1 or
itself. For example, 2, 3, 5, and 7 are prime numbers, but 4, 6, 8, and 9
are not.
Solution: The problem can be broken into the following tasks:
•For number = 2, 3, 4, 5, 6, ..., test whether the number is prime.
•Determine whether a given number is prime.
•Count the prime numbers.
•Print each prime number, and print 10 numbers per line.
PrimeNumber
34
Check Point
• Show the output of the following code.
int balance = 100;
while(true)
{
if(balance <9)
break;
balance -= 9;
}
cout<<balance<<endl;
35
int balance = 100;
while(true)
{
if(balance <9)
continue;
balance -= 9;
}
cout<<balance<<endl;
Summary
•
•
•
•
36
“while” and “do-while” loops
“for” loops
Difference between loop statements
Use of “break” and “continue”
Homework Questions
1. How many times is the following loop body
repeated? What’s the printout?
int balance = 100;
int consumed = 0;
while(true)
{
if(balance <10)
break;
consumed += 5;
if(!(consumed%10))
continue;
balance -= consumed;
cout<<balance<<endl;
}
2. Convert the above while loop into a for loop.
37