Professional Documents
Culture Documents
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
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
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
Switch
Exercise 4.4
Question 1 (Modify) Question 3 (Program)
#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; }
#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; }
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."; }
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
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
else
a. Exit the while statement
12
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
14
OUTPUT
10 9 8 7 6 5 4 3 2 1
15
#include <iostream> using namespace std; int main() { int i; i = 10; while (i >= 1) { cout << i << " "; i--; // subtract 1 from i }
return 0;
}
16
Fixed-count loop: tested expression is a counter that checks for a fixed number of repetitions
while (num < 11) or (num <=10)
Display Fahrenheit and Celsius temperatures, from 550 degrees C, in 5 degree increments
17
A First Book of C++ 4th Edition
celsius = 5;
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
#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
Q5
21
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
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
Example (Program 5.5): while statement accepts and displays four user-entered numbers
Numbers accepted and displayed one at a time
26
27
28
29
30
Program
31
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
#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
34
Format:
break;
35
for statements
Format:
1
36
37
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
Components of for statement are optional, but semicolons must always be present
Program
The for Statement (cont'd.)
41
42
int main() // all expressions inside for's parentheses { int count; for (count = 2 ; count <= 20 ; cout << count << " ", count = count + 2); return 0; }
Program
44
45
Same effect as using cin object within a while loop Provides interactive user input
46
Program
47
48
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
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
53
54
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
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
#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
59
Format:
do statement; while (expression);// dont forget final ; 60
A First Book of C++ 4th Edition
61
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
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
63
Creates a loop that executes 10 times and does nothing but increment count 64
A First Book of C++ 4th Edition
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
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
while is encountered
66
Summary (cont'd.)
Tested expression
Expressions that affect the tested expression Other loop statements can also be included as part of the altering list
67
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
3.00 5.00
DIFFERENT SETS OF QUESTION VENUE LR 13
69
EXERCISE
Question 15 216
70
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
#include <iostream> using namespace std; int main() { double grade; do { cout << "\nEnter a grade: "; cin >> grade; }
72
int main() { double grade; do { cout << "\nEnter a grade: "; cin >> grade; if(grade < 0 || grade > 100)
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
#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