Top Banner
Chapter 4 Loops §4.1 The “while” Loop §4.2 The “do-while” Loop §4.3 The “for” Loop §4.4 Nested loop §4.5 “break” and “continue” §4.6 Simple File Input and Output
32

Chapter 4 Loops

Jan 21, 2016

Download

Documents

Denise Mager

Chapter 4 Loops. §4.1 The “while” Loop §4.2 The “do-while” Loop §4.3 The “for” Loop §4.4 Nested loop §4.5 “break” and “continue” §4.6 Simple File Input and Output. Objectives. To master the usage of while , do - while , and for loops statements - PowerPoint PPT Presentation
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Chapter 4 Loops

Chapter 4 Loops

§4.1 The “while” Loop§4.2 The “do-while” Loop§4.3 The “for” Loop§4.4 Nested loop§4.5 “break” and “continue”§4.6 Simple File Input and Output

Page 2: Chapter 4 Loops

2

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X

Objectives To master the usage of while, do-while, and for

loops statements To understand the flow of control in loops To use Boolean expressions to control loops To know the similarities and differences of three

types of loops To know the use functionality of break and continue To know how to read and write data from/to a file

Page 3: Chapter 4 Loops

3

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X

§4.1 The “while” Loopwhile (loop-continuation-condition)

{

// loop-body;

Statement(s);

}

int count = 0;while (count < 100) { cout << "Welcome to C++!\n"; count++;}

Page 4: Chapter 4 Loops

4

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X

int count = 0;

while (count < 2)

{

cout << "Welcome to C++!";

count++;

}

(count < 2) is still true since count is 1

(count < 2) is false since count is 2 now

Increase count by 1count is 2 now

Print Welcome to C++

Trace while Loop

The loop exits. Execute the next statement after the loop.

Initialize count(count < 2) is truePrint Welcome to C++Increase count by 1count is 1 now

Page 5: Chapter 4 Loops

5

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X

Example: An Advanced Math Learning Tool

The Math subtraction tutor program in Listing 3.6, SubtractionTutor.cpp, generates just one question for each run.

You can use a loop to generate questions repeatedly.

Listing 4.1 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.

SubtractionTutorLoopSubtractionTutorLoop Run

Page 6: Chapter 4 Loops

6

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X

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;}

Page 7: Chapter 4 Loops

7

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X

Ending a Loop with a Sentinel Value Often the number of times a loop is executed is not predetermined. You may use an input value to signify the end of the loop. Such a value is known as a sentinel value.

Write a program that reads and calculates the sum of an unspecified number of integers.

The input 0 signifies the end of the input.

SentinelValueSentinelValue Run

Page 8: Chapter 4 Loops

8

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X

CautionDon’t use floating-point values for equality

checking in a loop control. Since floating-point values are

approximations, using them could result in imprecise counter values and inaccurate results.

double data = pow(sqrt(2.0), 2) - 2;if (data == 0) cout << "data is zero";else cout << "data is not zero";

Page 9: Chapter 4 Loops

9

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X

§4.2 The “do-while” Loop

do

{

// Loop body;

Statement(s);

} while (loop-continuation-condition);

Loop Continuation Condition?

true

Statement(s) (loop body)

false

“while”

“do-while”

Page 10: Chapter 4 Loops

10

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X

ExampleListing 4.3: a program that reads and

calculates the sum of an unspecified number of integers. The input 0 signifies the end of the input.

TestDoWhileTestDoWhile Run

Page 11: Chapter 4 Loops

11

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X

§4.3 The “for” Loopfor (initial-action; loop-continuation-condition; action-after-each-iteration) { // loop body; Statement(s);}

int i;

for (i = 0; i < 100; i++)

{

cout << "Welcome to C++!\n";

}

Page 12: Chapter 4 Loops

12

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X

int i;for (i = 0; i < 2; i++) { cout << "Welcome to C++!"; }

Execute adjustment statement i now is 2

Trace for Loop

Declare iExecute initializeri is now 0

(i < 2) is true since i is 0

Print Welcome to C++!Execute adjustment statement i now is 1

(i < 2) is still true since i is 1

Print Welcome to C++(i < 2) is false since i is 2Exit the loop. Execute the next

statement after the loop

Page 13: Chapter 4 Loops

13

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X

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;

1) sum=0;for (i=1; ; i++){ if (i<=100) break; sum += i;}

1) sum=0;for (i=1; i<=100; ){ sum += i;

i++;}

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.

Page 14: Chapter 4 Loops

14

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X

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

Page 15: Chapter 4 Loops

15

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X

“,” Operator“,”: concatenate expressions and the value of

the rightmost expression is the value of the whole comma expression

Example: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;

}}

Page 16: Chapter 4 Loops

16

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X

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.

TestSumTestSum Run

Page 17: Chapter 4 Loops

17

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X

Floating-point Numbers in Relational Expressions

int main() { // Initialize sum double sum = 0; double i=0; // Add 0.01, 0.02, ..., 0.99, 1 to sum for (i = 0.01; i <= 1.0; i = i + 0.01) sum += i; // Display result cout << "The sum is " << sum; return 0;

}

int main(){ // Initialize sum double sum = 0; double prei=0; double i;

// Add 0.01, 0.02, ..., 0.99, 1 to sum for (i = 0.01f; i <= 1.0f; i = i + 0.01f){ sum += i;

prei=i; } // Display result cout << "The sum is " << sum<<endl; cout<<setprecision(10)<<"i is increaded by "<<i-prei<<endl; cout<<"The final i is "<<i<<", and i-1.0 is " <<(i-1.0)<<endl;

return 0;}

Page 18: Chapter 4 Loops

18

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X

Which Loop to Use?

while (loop-continuation-condition) { // Loop body }

(a)

Equivalent

(b)

for ( ; loop-continuation-condition; ) { // Loop body }

for (initial-action; loop-continuation-condition; action-after-each-iteration) { // Loop body; }

(a)

Equivalent

(b)

initial-action; while (loop-continuation-condition) { // Loop body; action-after-each-iteration; }

while, do-while, and for, are expressively equivalent and mutually conversable.

Page 19: Chapter 4 Loops

19

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X

Which Loop to Use?“for”:

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.

Page 20: Chapter 4 Loops

20

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X

§4.4 Nested loopLoop with one outer loop and one or more

inner loops

Page 21: Chapter 4 Loops

21

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X

Nested Loops

Listing 4.5: a program that uses nested for loops to print a multiplication table.

TestMultiplicationTableTestMultiplicationTable Run

Page 22: Chapter 4 Loops

22

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X

Loop Example:Finding the Greatest Common Divisor

Problem: Write a program that prompts the user to enter two positive integers and finds their greatest common divisor.

Solution: Let the two input integers be n1 and n2. You can check whether k (for k = 2, 3, 4, and so on) is a common divisor for n1 and n2, until k is greater than n1 or n2.

GreatestCommonDivisorGreatestCommonDivisor RunRun

Page 23: Chapter 4 Loops

23

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X

Loop Example: Finding the Sales Amount

Problem: You have just started a sales job in a department store. Your pay consists of a base salary and a commission. The base salary is $5,000. The scheme shown below is used to determine the commission rate.

Sales Amount Commission Rate$0.01–$5,000 8 percent$5,000.01–$10,000 10 percent$10,000.01 and above 12 percent

Your goal is to earn $30,000 in a year. Write a program that will find out the minimum amount of sales you have to generate in order to make $30,000.

FindSalesAmountFindSalesAmount RunRun

Page 24: Chapter 4 Loops

24

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X

Loop Example: Displaying a Pyramid of Numbers

Problem: Write a program that prompts the user to enter an integer from 1 to 15 and displays a pyramid.

For example, if the input integer is 12, the output is shown below.

PrintPyramidPrintPyramid RunRun

Page 25: Chapter 4 Loops

25

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X

§4.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.

sum=0; mark=1; for ( i=0; ; ){ if (i>100) break; sum += i; i++;}if(i>0) avgnum = sum/I;…

Page 26: Chapter 4 Loops

26

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X

“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-after-

each-iteration.

sum=0; mark=1; for ( i=0; ; ){ if (i>100) continue; sum += i; i++;}if(i>0) avgnum = sum/I;…

Page 27: Chapter 4 Loops

27

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X

Examples

Use of “break”

Use of “continue”

TestBreakTestBreak

TestContinueTestContinue

Run

Run

Page 28: Chapter 4 Loops

28

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X

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.

PrimeNumberPrimeNumber RunRun

Page 29: Chapter 4 Loops

29

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X

§4.6 Simple File Input and OutputTo read input from the keyboard and write

output to the screen/console?“cin” and “cout”

To read and write data from/to a file?ifstream and ofstream

Page 30: Chapter 4 Loops

30

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X

Simple File Input and Output

SimpleFileOutputSimpleFileOutput RunRun

SimpleFileInputSimpleFileInput RunRun

To write to a file

To read from a file

Page 31: Chapter 4 Loops

31

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X

Testing End of a FileListing 4.3 read only three linesHow to determine when to stop reading if you

don’t know how many numbers are in a file?Use the eof() function to detect it.

Listing 4.14 revises Listing 4.13 to read all lines from the file numbers.txt.

TestEndOfFileTestEndOfFile RunRun

Page 32: Chapter 4 Loops

32

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X

Summary“while” and “do-while” loops“for” loopsDifference between loop stementsUse of “break” and “continue”Simple file I/OTesting of end-of-file