Professional Documents
Culture Documents
cases
. . .
default action(s)
Example
upcoming
Details
about characters
cout << "The character (" << 'a' << ") has the value " << static_cast< int > ( 'a' ) << endl;
Prints
The character (a) has the value 97
4
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
// code9.cpp // Counting letter grades. #include <iostream> using std::cout; using std::cin; using std::endl; // function main begins program execution int main() { int grade; // one grade int aCount = 0; // number of As int bCount = 0; // number of Bs int cCount = 0; // number of Cs int dCount = 0; // number of Ds int fCount = 0; // number of Fs cout << "Enter the letter grades." << endl << "Enter the EOF character to end input." << endl;
22 // loop until user types end-of-file key sequence break causes switch to end and 23 while ( ( grade = cin.get() ) != EOF ) { the program continues with the first 24 statement after the switch 25 // determine which grade was input 26 switch ( grade ) { // switch structure nested in while structure. 27 28 case 'A': // grade was uppercase A cin.get() uses dot notation. 29 case 'a': // or lowercase a This function gets 1 character from 30 ++aCount; // increment aCount the keyboard (after Enter pressed), 31 break; // necessary to exit switch Assignment statements and it is assigned to grade. 32 have a value, which is the 33 case 'B': // Compares grade (angrade was uppercase B the variable on the cin.get() returns EOF (end-ofsame as 34 case 'b': // or lowercase b int) to the++bCount; // incrementleft of the =. The value of numerical file) after the EOF character is 35 bCount representations of A// exita. and switch this statement is the same input, to indicate the end of data. 36 break; EOF may be ctrl-d or ctrl-z, 37 as the value returned by 38 case 'C': // grade was uppercase C depending on your OS. cin.get(). 39 case 'c': // or lowercase c 40 ++cCount; // increment cCount 41 break; // exit switch This can also be used to 42
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
case 'D': case 'd': ++dCount; break; case 'F': case 'f': ++fCount; break; case '\n': case '\t': case ' ': break; default:
// grade was uppercase D // or lowercase d // increment dCount // exit switch // grade was uppercase F // or lowercase f // increment fCount // exit switch // ignore newlines, // tabs, // and spaces in input // exit switch
This test is necessary because Enter is pressed after each letter grade is input. This adds a newline character that must be removed. Likewise, we want to ignore any whitespace.
Notice the default statement, which catches all other cases.
cout << "Incorrect letter grade entered." << " Enter a new grade." << endl;
61
62 63 64 65 66
break;
} // end switch } // end while
67 68 69 70 71 72 73 74 75 76 77 78
// output summary of results cout << "\n\nTotals for each letter grade are:" << "\nA: " << aCount // display number of A grades << "\nB: " << bCount // display number of B grades << "\nC: " << cCount // display number of C grades << "\nD: " << dCount // display number of D grades << "\nF: " << fCount // display number of F grades << endl; return 0; // indicate successful termination } // end function main
Enter the letter grades. Enter the EOF character to end input. a B c C A d f C E Incorrect letter grade entered. Enter a new grade. D A b ^Z
Repetition
structure
Example
Flowchart
of while loop
false
11
Counter-controlled
repetition
Definite
repetition
Number of repetitions known A class of ten students took a quiz. The grades (integers in the range 0 to 100) for this quiz are available to you. Determine the class average on the quiz.
Example
12
Pseudocode
for example:
Set total to zero Set grade counter to one While grade counter is less than or equal to ten Input the next grade Add the grade into the total Add one to the grade counter Set the class average to the total divided by ten Print the class average
Next:
13
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
// code1.cpp // Class average program with counter-controlled repetition. #include <iostream> using std::cout; using std::cin; using std::endl // function main begins program execution int main() { int total; // sum of grades input by user int gradeCounter; // number of grade to be entered next int grade; // grade value int average; // average of grades
14
22
21 23 24 25 26 27 28 29 30 31 32 33 34 35
// processing phase // loop 10 times // prompt for input // read grade from user // add grade to total cout << "Enter grade: "; cin >> grade; total = total + grade; } // termination phase average = total / 10;
The counter gets incremented each time the loop executes. // display result Eventually, the counter causes the cout << "Class average is " << average << endl; loop to end.
return 0; // indicate program ended successfully grade: 98 } // end function main grade: 76 grade: 71 grade: 87 grade: 83 grade: 90 grade: 57 grade: 79 grade: 82 grade: 94 average is 81
15
// integer division
36 Enter 37 Enter Enter Enter Enter Enter Enter Enter Enter Enter Class
Suppose
problem becomes:
Develop a class-averaging program that will process an random number of grades each time the program is run Unknown number of students How will program know when to end?
Sentinel
value
Indicates end of data entry Loop ends when sentinel input Sentinel chosen so it cannot be confused with regular input
-1 in this case
16
Many
Initialization
Initializes the program variables Input data, adjusts program variables Calculate and print the final results
Processing
Termination
17
1 2 3
// code2.cpp // Class average program with sentinel-controlled repetition. #include <iostream> using using using using std::cout; std::cin; std::endl; std::fixed; // parameterized stream manipulators
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
#include <iomanip>
using std::setprecision; // sets numeric output precision // function main begins program execution int main() { int total;
// sum of grades
18
29
30 31 32 33 34 35 36 37 38 39 40 41 42 43
// loop until sentinel value read from user while ( grade != -1 ) { total = total + grade;
Required because dividing two integers truncates the cout << "Enter grade, -1 toremainder. end: "; // prompt for input
cin >> grade; } // end while // termination phase // if user entered at least one grade ... // read next grade
44
45 46 47 48
if ( gradeCounter != 0 ) {
// calculate average of all grades entered average = static_cast<double> ( total ) / gradeCounter;
19
49 50 51 52 53 54 55 56 57 58 59
// display average with two digits of precision cout << "Class average is " << setprecision( 2 ) << fixed << average << endl; } // end if part of if/else else // if no grades were entered, output appropriate message cout << "No grades were entered" << endl; return 0; } // end function main grade, -1 to end: grade, -1 to end: grade, -1 to end: grade, -1 to end: grade, -1 to end: grade, -1 to end: grade, -1 to end: grade, -1 to end: grade, -1 to end: average is 82.50 // indicate program ended successfully
60 Enter Enter Enter Enter Enter Enter Enter Enter Enter Class
75 94 97 88 70 64 83 89 -1
fixed forces output to print setprecision(2)prints two digits past in fixed point format (not decimal point (rounded to fit precision). scientific notation). Also, forces trailing zeros and Programs that use this must include <iomanip> decimal point to print. include <iostream>
20
Problem
statement
A college has a list of test results (1 = pass, 2 = fail) for 10 students. Write a program that analyzes the results. If more than 8 students pass, print "Raise Tuition".
Notice
that
First refinement
Initialize variables Input the ten quiz grades and count passes and failures Print a summary of the exam results and decide if tuition should be raised
Refine
Initialize variables
to
Initialize passes to zero Initialize failures to zero Initialize student counter to one
22
Refine
Input the ten quiz grades and count passes and failures
to
While student counter is less than or equal to ten Input the next exam result If the student passed Add one to passes Else Add one to failures Add one to student counter
23
Refine
Print a summary of the exam results and decide if tuition should be raised
to
Print the number of passes Print the number of failures If more than eight students passed Print Raise tuition
Program
next
24
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
// code3.cpp // Analysis of examination results. #include <iostream> using std::cout; using std::cin; using std::endl; // function main begins program execution int main() { // initialize variables in declarations int passes = 0; int failures = 0; int result; // number of passes // number of failures // one exam result
19
20 21 22 23 24
25
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
// if result 1, increment passes; if/else nested in while if ( result = = 1 ) passes = passes + 1; else // if result not 1, increment failures failures = failures + 1; // increment studentCounter so loop eventually terminates studentCounter = studentCounter + 1; } // end while // termination phase; display number of passes and failures cout << "Passed " << passes << endl; cout << "Failed " << failures << endl; // if more than eight students passed, print "raise tuition" if ( passes > 8 ) // if/else nested in while
43
44 45 46 47
26
Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 2 Enter result (1 = pass, 2 = fail): 2 Enter result (1 = pass, 2 = fail): 1
27
Similar
to while structure
Makes loop continuation test at end, not beginning Loop body executes at least once
do { statement } while ( condition );
action(s)
Format
28
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
// code10.cpp // Using the do/while repetition structure. #include <iostream> using std::cout; using std::endl; // function main begins program execution int main() { int counter = 1; // initialize counter do { cout << counter << " "; // display counter } while ( ++counter <= 10 ); // end do/while
10
29
Counter-controlled
repetition requires
Name of control variable/loop counter Initial value of control variable Condition to test for final value Increment/decrement to modify control variable when looping
30
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
// code5.cpp // Counter-controlled repetition. #include <iostream> using std::cout; using std::endl; // function main begins program execution int main() { int counter = 1; // initialization while ( counter <= 10 ) { // repetition condition cout << counter << endl; // display counter ++counter; // increment
} // end while
return 0; // indicate successful termination } // end function main
31
1 2 3 4 5 6 7 8 9 10
32
The
declaration
int counter = 1;
Names counter Declares counter to be an integer Reserves space for counter in memory Sets counter to an initial value of 1
33
General
Example
for( int counter = 1; counter <= 10; counter++ ) cout << counter << endl;
34
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// code6.cpp // Counter-controlled repetition with the for structure. #include <iostream> using std::cout; using std::endl; // function main begins program execution int main() { // Initialization, repetition condition and incrementing // are all included in the for structure header. for ( int counter = 1; counter <= 10; counter++ ) cout << counter << endl; return 0; // indicate successful termination } // end function main
35
1 2 3 4 5 6 7 8 9 10
36
for
Initialization
and increment
37
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
// code7.cpp // Summation with for. #include <iostream> using std::cout; using std::endl; // function main begins program execution int main() { int sum = 0; // initialize sum // sum even integers from 2 through 100 for ( int number = 2; number <= 100; number += 2 ) sum += number; // add number to sum
cout << "Sum is " << sum << endl; // output sum return 0; // successful termination
} // end function main
Sum is 2550
38
Program
A person invests $1000.00 in a savings account yielding 5 percent interest. Assuming that all interest is left on deposit in the account, calculate and print the amount of money in the account at the end of each year for 10 years. n Use the following formula for determining these amounts: a = p(1+r) p is the original amount invested (i.e., the principal), r is the annual interest rate, n is the number of years and a is the amount on deposit at the end of the nth year
39
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
// code8.cpp // Calculating compound interest. #include <iostream> using std::cout; using std::endl; using std::ios; using std::fixed; #include <iomanip> using std::setw; using std::setprecision;
<cmath> header needed for the pow function (program will not compile without it).
#include <cmath> // enables program to use function pow // function main begins program execution int main()
19
20 21 22 23
{
double amount; double rate = .05; // amount on deposit // interest rate double principal = 1000.0; // starting principal
40
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
// output table column heads cout << "Year" << setw( 21 ) << "Amount on deposit" << endl;
Sets the field width to at least 21 characters. If output less than 21, it is right-justified.
pow(x,y) = x raised to the yth power.
} // end for
return 0; // indicate successful termination } // end function main
41
Year 1 2 3 4 5 6 7 8 9 10
Amount on deposit 1050.00 1102.50 1157.63 1215.51 1276.28 1340.10 1407.10 1477.46 1551.33 1628.89
Numbers are right-justified due to setw statements (at positions 4 and 21).
42
break
statement
Immediate exit from while, for, do/while, switch Program continues with first statement after structure
Common
uses
43
1 2 3
// code11.cpp // Using the break statement in a for structure. #include <iostream> using std::cout; using std::endl; // function main begins program execution int main() { int x; // x declared here so it can be used after the loop // loop 10 times for ( x = 1; x <= 10; x++ ) { // if x is 5, terminate loop if ( x == 5 ) break;
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
cout << x << " "; // display value of x } // end for cout << "\nBroke out of loop when x became " << x << endl;
44
45
continue
statement
Used in while, for, do/while Skips remainder of loop body Proceeds with next iteration of loop
while
for
structure
46
Using
For loop write a program for displaying grades of students from A-F
1-47