Vous êtes sur la page 1sur 75

A First Book of C++

Chapter 5 Repetition

Objectives
In this chapter, you will learn about:
The while Statement Interactive while Loops The for Statement The do while Statement Common Programming Errors Additional Testing Techniques

A First Book of C++ 4th Edition

CSC1100 Schedule
Wk # 1 Start date 10/09/2012 12/09/2012 Lecture/Tutorial Chapter 1: Getting Started Chapter 2: Data Types, Declarations and Displays Chapter 3: Assignments and Interactive Input QUIZ 1 ( Second Class) Assignment/Quizzes

17/09/2012
19/09/2012

24/09/2012

26/09/2012
4 5 1/10/2012 3/10/2012 8/10/2012 10/10/2012 6 15/10/2012 17/10/2012
22 28/10/2012

Chapter 4: Selection

ASSIGNMENT 1 (10TH & 11th OCTOBER 2012) (IN CLASS OPEN TEXT BOOK ONLY)

Chapter 5: Repetition

19/10/2012 MID TERM EXAM (10.0012.00)

MID-SEMESTER BREAK

CSC1100 Schedule
Wk # 7 Start date 29/10/2012 31/10/2012 9 10 11 12 13 14 12/11/2012 14/11/2012 19/11/2012 21/11/2012 26/11/2012 28/11/2012 3/12/2012 5/12/2012 10/12/2012 12/12/2012 17/12/2012 19/12/2012 Chapter 16: Data Structures Chapter 8 & 9: Pointers and I/O Stream GROUP PROJECT GROUP PROJECT Chapter 6: Modularity using Functions Lecture/Tutorial Chapter 14: The String Class and Exception Handling Assignment/Quizzes QUIZ 2 ASSIGNMENT 2

QUIZ 3
ASSIGNMENT 3

GROUP PROJECT
GROUP PROJECT GROUP PROJECT GROUP PROJECT

Exercises & Homework


If-else
Exercise 4.3
Question 3 (Program) Question 9 ( Program)

Switch
Exercise 4.4
Question 1 (Modify) Question 3 (Program)

A First Book of C++ 4th Edition

#include <iostream> using namespace std; int main() { double grade; cout << "Enter the grade: "; cin >> grade; if (grade >= 90) cout << "Your grade is an A"; else if (grade < 90 && grade >= 80) cout << "Your grade is a B"; else if (grade < 80 && grade >= 70) cout << "Your grade is a C"; else if (grade < 70 && grade >= 60) cout << "Your grade is a D"; else if (grade < 60) cout << "Your grade is an F"; system("pause"); return 0; }

A First Book of C++ 4th Edition

#include <iostream> using namespace std; int main() { double temp; char letter; cout << "Enter the temperature followed by a letter indicating c for Celsius or f for Fahrenheit: "; cin >> temp >> letter; if (letter == 'f' || letter == 'F') { temp = (5.0 / 9.0) * (temp - 32.0); cout << "The temperature is " << temp << " c" << endl; } else if (letter == 'c' || letter == 'C') { temp = (9.0 / 5.0) * temp + 32.0; cout << "The temperature is " << temp << " f" << endl; } else cout << "Incorrect data has been entered"; system("pause"); return 0; }

A First Book of C++ 4th Edition

switch (letterGrade) { case 'A': cout << "The numerical grade is between 90 and 100"; break; case 'B': cout << "The numerical grade is between 80 and 89.9"; break; case 'C': cout << "The numerical grade is between 70 and 79.9"; break; case 'D': cout << "How are you going to explain this one?"; break; default: cout << "Of course I had nothing to do with the grade."; cout << "\nIt must have been the professor's fault."; }

A First Book of C++ 4th Edition

int main() { int code; cout << "Enter the disk drive code: "; cin >> code; switch (code) { case 1: cout << "The disk drive has a capacity of 2GB\n"; break; case 2: cout << "The disk drive has a capacity of 4GB\n"; break; case 3: cout << "The disk drive has a capacity of 16GB\n"; break; case 4: cout << "The disk drive has a capacity of 32GB\n"; break; }

return 0;
A First Book of C++ 4th Edition

The while statement


10
A First Book of C++ 4th Edition

The while Statement


A general repetition statement

Format:
while (expression) statement;

Function:
expression is evaluated the same as an if-else statement Statement following expression executed repeatedly as long as expression has non-zero value
11
A First Book of C++ 4th Edition

The while Statement (cont'd.)

Steps in execution of while statement:


1. Test the expression 2. If the expression has a non-zero (true) value
a. Execute the statement following the parentheses
b. Go back to step 1

else
a. Exit the while statement

12

A First Book of C++ 4th Edition

Forces the program to go back to STEP 1: reevaluating the expression While statements will loops back on itself to recheck the expression until it evaluates to 0 (false)

13

A First Book of C++ 4th Edition

The while Statement (cont'd.)

14

A First Book of C++ 4th Edition

OUTPUT
10 9 8 7 6 5 4 3 2 1

15

A First Book of C++ 4th Edition

#include <iostream> using namespace std; int main() { int i; i = 10; while (i >= 1) { cout << i << " "; i--; // subtract 1 from i }

return 0;
}

16

A First Book of C++ 4th Edition

The while Statement (cont'd.)


Infinite loop: one that never ends
The program keep on displaying numbers until you realize that it does not work normally

Fixed-count loop: tested expression is a counter that checks for a fixed number of repetitions
while (num < 11) or (num <=10)

Variation: counter is incremented by a value other than 1 Example:


Celsius-to-Fahrenheit temperature conversion

Display Fahrenheit and Celsius temperatures, from 550 degrees C, in 5 degree increments
17
A First Book of C++ 4th Edition

The while Statement (cont'd.)

celsius = 5;

// starting Celsius value

while (celsius <= 50) { fahren = (9.0/5.0) * celsius + 32.0; cout << setw(4) << celsius << setw(13) << fahren << endl; celsius = celsius + 5; }

Fixed-count loops

18

A First Book of C++ 4th Edition

#include <iostream> #include <iomanip> using namespace std; // a program to convert Celsius to Fahrenheit int main() { const int MAXCELSIUS = 50; const int STARTVAL = 5; const int STEPSIZE = 5; int celsius; double fahren; cout << "DEGREES DEGREES\n" << "CELSIUS FAHRENHEIT\n" << "------- ----------\n"; celsius = STARTVAL; // set output formats for floating-point numbers only cout << setiosflags(ios::showpoint) << setiosflags(ios::fixed)<< setprecision(2); while (celsius <= MAXCELSIUS) { fahren = (9.0/5.0) * celsius + 32.0; cout << setw(4) << celsius << setw(13) << fahren << endl; celsius = celsius + STEPSIZE; } return 0; }

Fixed-count loops

Class Exercise

Exercise 5.1
Q 5 (Program)

Q 6 ( Program)
Q 7 ( Program)

20

A First Book of C++ 4th Edition

Q5

21

A First Book of C++ 4th Edition

int main() { int years = 1; int depreciation = 4000; int start_val = 28000; cout << "\n"; cout << " END-OF-YEAR ACCUMULATED\n"; cout << " YEAR DEPRECIATION VALUE DEPRECIATION\n"; cout << " ---- ------------ ----------- ------------\n"; while (years <= 7) { cout << setw(5) << years << setw(14) << depreciation << setw(16) << start_val - (depreciation * years) << setw(16) << (depreciation * years) << '\n'; years ++; }

return 0; }

22

A First Book of C++ 4th Edition

int main() { const int MAXFEET = 30; const int STARTVAL = 3; const int STEPSIZE = 3; int feet; double meters; cout << " FEET METERS\n" << " \n"; feet = STARTVAL; // set output formats for floating point numbers only cout << setiosflags(ios::fixed)<< setiosflags(ios::showpoint)<< setprecision(2); while (feet <= MAXFEET) { meters = feet / 3.28; cout << setw(4) << feet<< setw(13) << meters << endl; feet = feet + STEPSIZE; }

system("pause"); return 0; }

23

int main() { const int MAXHOURS = 4; const double STARTVAL = 0.5; const double STEPSIZE = 0.5; const int DISTANCE = 55; double hours; double distance; cout << " HOUR DISTANCE\n" << " ----------- \n"; hours = STARTVAL; distance = 0; cout << setiosflags(ios::fixed) << setiosflags(ios::showpoint) << setprecision(2); while (hours <= MAXHOURS) { distance = DISTANCE * hours; cout << setw(5) << hours<< setw(15) << distance << endl; hours = hours + STEPSIZE; } system("pause"); return 0; }

24

A First Book of C++ 4th Edition

Interactive while Loops


25
A First Book of C++ 4th Edition

Interactive while Loops

Combining interactive data entry with the repetition of a while statement


Produces very powerful and adaptable programs

Example (Program 5.5): while statement accepts and displays four user-entered numbers
Numbers accepted and displayed one at a time

26

A First Book of C++ 4th Edition

27

A First Book of C++ 4th Edition

Interactive while Loops (cont'd.)


Sample run of Program 5.5:
This program will ask you to enter 4 numbers.
Enter a number: 26.2 The number entered is 26.2 Enter a number: 5

The number entered is 5


Enter a number: 103.456 The number entered is 103.456 Enter a number: 1267.89

The number entered is 1267.89

28

A First Book of C++ 4th Edition

Interactive while Loops (cont'd.)

Example (Program 5.6): adding a single number to a total


A number is entered by the user Accumulating statement adds the number to total

total = total + num;


A while statement repeats the process

29

A First Book of C++ 4th Edition

Interactive while Loops (cont'd.)

30

A First Book of C++ 4th Edition

Program

31

A First Book of C++ 4th Edition

Interactive while Loops (cont'd.)


Sample run of Program 5.6:

This program will ask you to enter 4 numbers. Enter a number: 26.2 The total is now 26.2 Enter a number: 5 The total is now 31.2 Enter a number: 103.456 The total is now 134.656 Enter a number: 1267.89 The total is now 1402.546

32

The final total is 1402.546


A First Book of C++ 4th Edition

#include <iostream> using namespace std; int main() { const int MAXNUMS = 4; int count; double num, total, average; cout << "\nThis program will ask you to enter "<< MAXNUMS << " numbers.\n\n"; count = 1; total = 0; while (count <= MAXNUMS) { cout << "Enter a number: "; cin >> num; total = total + num; count++; } count--; average = total / count; cout << "\nThe average of the numbers is " << average << endl; return 0; }

33

Sentinels

Sentinels
Data values used to signal the start or end of data series

Values must be selected so as not to conflict with legitimate data values

34

A First Book of C++ 4th Edition

break and continue Statements


break: forces immediate exit from structures
Use in switch statements:
The desired case has been detected and processed

Use in while, for, and do-while statements:


An unusual condition is detected

Format:
break;

35

A First Book of C++ 4th Edition

break and continue Statements (cont'd.)


continue: causes the next iteration of the loop to begin immediately
Execution transferred to the top of the loop Applies only to

while, do-while, and

for statements
Format:
1

36

A First Book of C++ 4th Edition

The Null Statement

Used where a statement is syntactically required but no action is called for


A do-nothing statement
Typically used with while or for statements

37

A First Book of C++ 4th Edition

The for Statement


38
A First Book of C++ 4th Edition

The for Statement

Same function as the while statement but in different form for (initializing list; expression; altering list) statement; Function: statement executed while expression has non-zero (true) value

Components:
Initializing list: initial value of expression Expression: a valid C++ expression Altering list: statements executed at end of each for loop to alter value of expression 39
A First Book of C++ 4th Edition

The for Statement (cont'd.)


Components of for statement correspond to operations performed in while statement
Initialization Expression evaluation Altering of expression values

Components of for statement are optional, but semicolons must always be present

Figure 5.5 ( 202)


40
A First Book of C++ 4th Edition

Program
The for Statement (cont'd.)

41

A First Book of C++ 4th Edition

The for Statement (cont'd.)

Program 5.9 modified: initializer outside for loop

42

A First Book of C++ 4th Edition

5.9 (b), 5.9 (c)

int main() // all expressions inside for's parentheses { int count; for (count = 2 ; count <= 20 ; cout << count << " ", count = count + 2); return 0; }

Separate with comma 43

A First Book of C++ 4th Edition

Program

44

A First Book of C++ 4th Edition

The for Statement (cont'd.)


When Program 5.10 is run, the display produced is:
NUMBER _ _ _ _ _ _ 1 2 3 4 5 6 7 8 9 10 SQUARE _ _ _ _ _ _ 1 4 9 16 25 36 49 64 81 100 CUBE _ _ _ _ 1 8 27 64 125 216 343 512 729 1000

45

A First Book of C++ 4th Edition

Interactive for Loops

Same effect as using cin object within a while loop Provides interactive user input

46

A First Book of C++ 4th Edition

Program

47

A First Book of C++ 4th Edition

Interactive for Loops (cont'd.)

Program 5.11: for statement creates a loop


Loop executed five times

Actions performed in each loop


User prompted to enter a number Number added to the total

48

A First Book of C++ 4th Edition

Interactive for Loops (cont'd.)

ARE THESE STATEMENTS VALID?

1. for (total = 0.0, count = 0; count < MAXCOUNT; count++)


2. for (double total = 0.0, int count = 0; count < MAXCOUNT; count++) EXPLAIN
49
A First Book of C++ 4th Edition

Interactive for Loops (cont'd.)


Initialization variations:
Alternative 1: initialize total outside the loop and count inside the loop as in Program 5.11 Alternative 2: initialize both total and count inside loop

for (total = 0.0, count = 0; count < MAXCOUNT; count++)


Alternative 3: initialize and declare both total and count inside loop

for (double total = 0.0, int count = 0; count < MAXCOUNT; count++)
50
A First Book of C++ 4th Edition

Nested Loops
A loop contained within another loop Example: for(i = 1; i <= 5; i++) { cout << "\ni is now " << i << endl; // start of outer loop

for(j = 1; j <= 4; j++)


{ cout << " j = " << j; } } 51
A First Book of C++ 4th Edition

// start of inner loop

// end of inner loop // end of outer loop

Nested Loops (cont'd.)


Outer (first) loop:
Controlled by value of i

Inner (second) loop:


Controlled by value of j

Rules:
For each single trip through outer loop, inner loop runs through its entire sequence Different variable to control each loop Inner loop statements contained within outer loop

52

A First Book of C++ 4th Edition

Nested Loops (cont'd.)

53

A First Book of C++ 4th Edition

CLASS EXERCISE 12 ( a and b)


QUESTION 12 ( page 215)

QUESTION 12 b ( page 215)

54

A First Book of C++ 4th Edition

12 a
int main() { int yr; double amount = 1000., total; for (total = amount, yr = 1; yr <=10; yr++) { total = total * 1.03; cout << "The balance at the end of " << yr << " years is $" << setiosflags(ios::showpoint) << setiosflags(ios::fixed) << setw(8) << setprecision(2) << total << endl; } system("pause"); return 0; } 55
A First Book of C++ 4th Edition

#include <iostream> #include <iomanip> using namespace std; int main() { int yr; double amount, total; cout << "\nPlease enter initial deposit amount: "; cin >> amount; for (total = amount, yr = 1; yr <=10; yr++) { total = total * 1.03; cout << "The balance at the end of " << yr << " years is $" << setiosflags(ios::showpoint) << setiosflags(ios::fixed) << setw(8) << setprecision(2) << total << endl; } system("pause"); return 0; }

56

A First Book of C++ 4th Edition

int main() { int yr = 1, years; double amount, interest, total; cout << "\nPlease enter initial deposit amount: "; cin >> amount; cout << "\nPlease enter number of years: "; cin >> years; cout << "\nPlease enter interest rate as a decimal value (ex. .03): "; cin >> interest; for (total = amount; yr <=years; yr++) { total = total + (total * interest); cout << "The balance at the end of " << yr << " years is $" << setiosflags(ios::showpoint) << setiosflags(ios::fixed) << setw(8) << setprecision(2) << total << endl; } system("pause"); return 0; }

57

A First Book of C++ 4th Edition

#include <iostream> #include <iomanip> using namespace std; int main() { int yr = 1, years; double amount, total; cout << "\nPlease enter initial deposit amount: "; cin >> amount; cout << "\nPlease enter number of years: "; cin >> years; for (total = amount; yr <=years; yr++) { total = total * (1 + 0.03); cout << "The balance at the end of " << yr << " years is $" << setiosflags(ios::showpoint) << setiosflags(ios::fixed) << setw(8) << setprecision(2) << total << endl; } system("pause"); return 0; }

58

A First Book of C++ 4th Edition

The do-while Statement

59

A First Book of C++ 4th Edition

The do-while Statement


A repetition statement that evaluates an expression at the end of the statement
Allows some statements to be executed before an expression is evaluated for and while evaluate an expression at the beginning of the statement

Format:
do statement; while (expression);// dont forget final ; 60
A First Book of C++ 4th Edition

61

A First Book of C++ 4th Edition

Validity Checks
Provided by do-while statement through filtering of userentered input
Example:
do

{
cout << "\nEnter an identification number: "; cin >> idNum; if (idNum < 100 || idNum > 1999)

{
cout << "\n An invalid number was just entered" << "\nPlease check the ID number and reenter";

else
break; // break if a valid ID number was entered

62

} while(1); // this expression is always true

Common Programming Errors

Off by one errors: loop executes one time too many or one time too few
Initial and final conditions to control loop must be carefully constructed

Inadvertent use of assignment operator, =, in place of the equality operator, ==


This error is not detected by the compiler

63

A First Book of C++ 4th Edition

Common Programming Errors (cont'd.)


Using the equality operator when testing doubleprecision operands
Do not test expression (fnum == 0.01) Replace by a test requiring absolute value of
(fnum 0.01) < epsilon for very small epsilon

Placing a semicolon at end of the for statement parentheses:


for (count = 0; count < 10; count ++); total = total + num;

Creates a loop that executes 10 times and does nothing but increment count 64
A First Book of C++ 4th Edition

Common Programming Errors (cont'd.)


Using commas instead of semicolons to separate items in a for statement:
for (count = 1, count < 10, count ++) Commas should be used to separate items within the separating and initializing lists

Changing the value of the control variable used in the tested condition both inside the body of a for loop and in its altering list Omitting the final semicolon from the do-while statement

65

A First Book of C++ 4th Edition

Summary
while, for, and do-while statements create loops
These statements evaluate an expression
On the basis of the expression value, either terminate the loop or continue with it

Each pass through the loop is called a repetition or iteration

while checks expression before any other statement in the loop


Variables in the tested expression must have values assigned before

while is encountered

66

A First Book of C++ 4th Edition

Summary (cont'd.)

The for statement: fixed-count loops


Included in parentheses at top of loop:
Initializing expressions

Tested expression
Expressions that affect the tested expression Other loop statements can also be included as part of the altering list

67

A First Book of C++ 4th Edition

Summary (cont'd.)

The do-while statement checks its expression at the end of the loop
Body of the loop must execute at least once do-while loop must contain statement(s) that either:
Alter the tested expressions value or Force a break from the loop

68

A First Book of C++ 4th Edition

MID TERM EXAM

CHAPTERS COVERED : UNTIL CHAPTER 5 2 SESSION: 40 students per session


11.00 1.00

3.00 5.00
DIFFERENT SETS OF QUESTION VENUE LR 13

69

A First Book of C++ 4th Edition

EXERCISE

Question 15 216

Question 5.4 a - 220

70

A First Book of C++ 4th Edition

using namespace std; int main() { int i, j; double num, total; double average; for (i = 1; i < 5; i++) //for the 4 experiments { total = 0; //clear the total for this experiment cout << "\nExperiment " << i << endl; for(j = 1; j < 7; j++) //for the 6 test results { cout << "Enter test result " << j << ": "; cin >> num; total = num + total; } average = total / (j-1); cout << "Experiment " << i << " average: " << average << endl;

}
system("pause"); return 0; }

71

A First Book of C++ 4th Edition

#include <iostream> using namespace std; int main() { double grade; do { cout << "\nEnter a grade: "; cin >> grade; }

while (grade < 0 || grade > 100);


cout << "\nThe grade entered was: " << grade << endl; system("pause"); return 0; }

72

A First Book of C++ 4th Edition

#include <iostream> using namespace std;

int main() { double grade; do { cout << "\nEnter a grade: "; cin >> grade; if(grade < 0 || grade > 100)

cout << "An invalid grade has been entered! "


<< "Please reenter a valid grade." << endl; else break; } while (1);

cout << "\nThe grade entered was: " << grade << endl;

system("pause"); return 0;

73

#include <iostream> using namespace std; int main() { double grade; do { cout << "\nEnter a grade (enter 999 to exit): "; cin >> grade; if(grade == 999) break; else if(grade < 0 || grade > 100) cout << "An invalid grade has been entered! " << "Please reenter a valid grade." << endl; else break; } while (1); if(grade != 999) cout << "\nThe grade entered was: " << grade << endl; system("pause"); return 0; }

74

A First Book of C++ 4th Edition

#include <iostream> using namespace std; int main() { double grade; int invalid = 0; do { cout << "\nEnter a grade: "; cin >> grade; if(grade < 0 || grade > 100) { invalid++; if(invalid == 5) break; cout << "An invalid grade has been entered! " << "Please reenter a valid grade." << endl; } else break; } while (1); if(invalid != 5) cout << "\nThe grade entered was: " << grade << endl; system("pause"); return 0; }

75

Vous aimerez peut-être aussi