Chapter 3 Control Statements Objectives Enhance problemsolving techniques
Chapter 3, Control Statements
Objectives: • Enhance problem-solving techniques through Developing algorithms Stepwise refinement • Review of basic control structures: if…else statements while repetition counter-controlled and sentinel-controlled repetition © 1992 -2014 by Pearson Education, Inc. All Rights Reserved.
Relational Operators Operator > < >= <= == != Meaning Greater than Less than Greater than or equal to Less than or equal to Equal to Not equal to
Values of True & False # include <iostream> using namespace std; int main () 1? True { int True, False, X=5, Y=10; True = X < Y; False = Y == X; 0? cout << “True is ” << True << endl; False cout << “False is ” << False << endl; return 0; } 5 10 x y True is 1 False is 0 _ _
What is the output? # include <iostream> using namespace std; int main () { int A = 0, B = 2, X = 4, Y = 0; cout << (A == B) << endl; cout << (A != Y) << endl; cout << (B <= X) << endl; cout << (Y > A) << endl; return 0; } 0 _ 1 _ 0 2 4 0 A B X Y
if Statements examples Statements if (Hours > 40) Over. Time =1; Outcome Assigns 1 to Over. Time only when Hours > 40 Displays message only when Value is > 32. If (Value > 32) cout << “Invalid numbern”; Pay. Rate by 2 only if (Over. Time == 1) Multiplies when Over. Time Payrate *= 2; is = 1
if Statement structure if (expression) { statement; // Place as many statement; // statements here statement; // as needed }
What’s True • • Any non-zero value is considered true by the if statement When a relational expression is true it has the value 1. When a relational expression is false it has a value of 0. an expression that has the value 0 is considered false by the if statement. An expression that has any value other than 0 is considered true by the if statement.
What’s True int Value = 5; if (Value) cout << “It is True!”; int X = -2; int Y = -3; if (X + Y) cout << “It is True!”;
What’s True int Value = 0; if (Value) cout << “It is True!”; int X = -2; int Y = 2; if (X + Y) cout << “It is True!”;
Warning = is not == int X = 0; if (X = 2) cout << “It is True!”;
#include <iostream> #include <iomanip> using namespace std; int main() { int Score 1, Score 2, Score 3; bool High. Score= false; float Average; cout << “Enter 3 test scores and I” <<“will average them: “; cin >> Score 1 >> Score 2 >> Score 3; Average = (Score 1 + Score 2 + Score 3)/3. 0;
if (Average > 95) High. Score = true; //Set the flag variable cout << fixed << showpoint << setprecision(1); cout << “Your average is “ <<Average << endl; if (High. Score) { cout << “Congratulations!n”; cout << “That’s a high score. n” cout << “You deserve a pat on the back!n”; } // end of if return 0; } // end of main
if/else Statement structure if (expression) { statement; } else { statement; }
#include <iostream> using namespace std; int main() { int Test. Score; char Grade; 88 ? Test. Score ? Grade cout << “Enter your numeric test score” << “and I willn”; cout << “tell you the letter grade you” << “earned: “; cin >> Test. Score;
if (Test. Score < 60) 88 Grade = ‘F’; ? Test. Score else if (Test. Score < 70) Grade = ‘D’; B ? else if (Test. Score < 80) Grade = ‘C’; else if (Test. Score < 90) Grade = ‘B’; else if (Test. Score<=100) Grade = ‘A’; cout << “Your grade ” << “is ” << Grade << “. n”; }
if (Test. Score < 60) Grade = ‘F’; if (Test. Score < 70) Grade = ‘D’; if (Test. Score < 80) Grade = ‘C’; if (Test. Score < 90) Grade = ‘B’; if (Test. Score < = 100) Grade = ‘A’;
Using if / else if statements #include <iostream> using namespace std; int main() { int Choice, Months; float Charges; ? Choice ? cout << “tHealth Club Member” Months << “ship Menunn”; cout << “ 1. Standard Adultn”; ? . ? Charges cout << “ 2. Childn”; cout << “ 3. Senior Citizenn”; cout << “ 4. Quit the programnn”; cout << “Enter your choice: ”;
cin >> Choice; cout << fixed << showpoint << setprecision(2); 3 ? Choice ? Months ? . ? Charges
if (Choice ==1) { //code for standard adult } else if (Choice == 2) { //code for child } else if (Choice == 3) { //code for senior citizen } else if (Choice != 4) { //code for incorrect entry } return 0; } 3 ? Choice ? Months ? . ? Charges
if (Choice ==1) { //code for standard adult } else if (Choice == 2) { //code for child } 3 ? Choice else if (Choice == 3) { cout << “n. How many ” 6 ? << “ months? ”; Months cin >> Months; Charges = Months * 30. 00; 180. 00 ? . ? cout << “The total charge is $” Charges << Charge << endl; } else if (Choice != 4) { //code for incorrect entry } }
int main() { char Employed, Recent. Grad; cout << “Are you employed? ”; cin >> Employed; cout << “Have you graduated? ”; cin >> Recent. Grad; if (Employed == ‘Y’) { if (Recent. Grad == ‘Y’) { cout << “You qualify”; cout << “For a special interest rate”; } else cout << “You must have graduated to qualify”; } else cout << “you must be employed to qualify”;
int main () { int x=9, y=11; if (x < 10) if (y > 10) cout << “*****n”; else cout << “#####n”; cout << “$$$$$n”; return 0; } 9 11 x y ***** $$$$$ _ _
int main () { int x=11, y=9; if (x < 10) if (y > 10) cout << “*****n”; else cout << “#####n”; cout << “$$$$$n”; return 0; } 11 9 x y $$$$$ _
int main () { int x=9, y=11; if (x < 10) { if (y > 10) cout << “*****n”; } else { cout << “#####n”; cout << “$$$$$n”; } } 9 11 x y ***** _
int main () { int x=11, y=9; if (x < 10) { if (y > 10) cout << “*****n”; } else { cout << “#####n”; cout << “$$$$$n”; } return 0; } 11 9 x y ##### $$$$$ _ _
Introduction to problem solving Before writing a program to solve a problem, we must have a thorough understanding of the problem and a carefully planned approach to solving it. When writing a program, we must also understand the types of building blocks that are available and employ proven program construction techniques. © 1992 -2014 by Pearson Education, Inc. All Rights Reserved.
Algorithms Any solvable computing problem can be solved by the execution a series of actions in a specific order. An algorithm is procedure for solving a problem in terms of ◦ the actions to execute and ◦ the order in which the actions execute Specifying the order in which statements (actions) execute in a computer program is called program control. © 1992 -2014 by Pearson Education, Inc. All Rights Reserved.
Pseudocode Pseudocode (or “fake” code) is an artificial and informal language that helps you develop algorithms. Similar to everyday English Convenient and user friendly. Helps you “think out” a program before attempting to write it. Carefully prepared pseudocode can easily be converted to a corresponding C++ program. Normally describes only executable statements. Declarations (that do not have initializers or do not involve constructor calls) are not executable statements. Fig. 4. 1 corresponds to the algorithm that inputs two integers from the user, adds these integers and displays their sum. © 1992 -2014 by Pearson Education, Inc. All Rights Reserved.
Prompt the user to enter the first integer Input the first integer Prompt the user to enter the second integer Input the second integer Add first and seond integer store results Display result © 1992 -2014 by Pearson Education, Inc. All Rights Reserved.
if…else Double-Selection Statement (cont. ) Nested if…else statements test for multiple cases by placing if…else selection statements inside other if…else selection statements. If student’s grade is greater than or equal to 90 Print “A” Else If student’s grade is greater than or equal to 80 Print “B” Else If student’s grade is greater than or equal to 70 Print “C” Else If student’s grade is greater than or equal to 60 Print “D” Else Print “F” © 1992 -2014 by Pearson Education, Inc. All Rights Reserved.
if…else Double-Selection Statement (cont. ) This pseudocode can be written in C++ as if ( student. Grade >= 90 ) // 90 and above gets "A" cout << "A"; else if ( student. Grade >= 80 ) // 80 -89 gets "B" cout << "B"; else if ( student. Grade >= 70 ) // 70 -79 gets "C" cout << "C"; else if ( student. Grade >= 60 ) // 60 -69 gets "D" cout << "D"; else // less than 60 gets "F" cout << "F"; If student. Grade is greater than or equal to 90, the first four conditions are true, but only the output statement after the first test executes. Then, the program skips the else-part of the “outermost” if…else statement. © 1992 -2014 by Pearson Education, Inc. All Rights Reserved.
if…else Double-Selection Statement (cont. ) Most programmers write the preceding statement as if ( student. Grade >= 90 ) cout << "A"; else if ( student. Grade >= cout << "B"; else if ( student. Grade >= cout << "C"; else if ( student. Grade >= cout << "D"; else // less than 60 gets cout << "F"; // 90 and above gets "A" 80 ) // 80 -89 gets "B" 70 ) // 70 -79 gets "C" 60 ) // 60 -69 gets "D" "F" The two forms are identical except for the spacing and indentation, which the compiler ignores. The latter form is popular because it avoids deep indentation of the code to the right, which can force lines to wrap. © 1992 -2014 by Pearson Education, Inc. All Rights Reserved.
while Repetition Statement A repetition statement (also called a looping statement or a loop) allows you to specify that a program should repeat an action while some condition remains true. While there are more items on my shopping list Purchase next item and cross it off my list © 1992 -2014 by Pearson Education, Inc. All Rights Reserved.
Problem statement: Write a program that will allow the user to enter the grades for exam 1 of ten different students Calculate and display the total of all grades and the class average. © 1992 -2014 by Pearson Education, Inc. All Rights Reserved.
Set total to zero Set grade counter to one While grade counter is less than or equal to ten prompt the user to enter the next grade 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 total of the grades for all students in the class Print the class average © 1992 -2014 by Pearson Education, Inc. All Rights Reserved.
#include <iostream> using namespace std; int main() { int total{0}; // new style int total =0; // old style unsigned int grade. Counter{1}; // old style unsigned int grade. Counter = 1; while (grade. Counter <=10) { cout << “Enter grade: “; int grade; cin >> grade; total = total + grade; grade. Counter = grade. Counter + 1; } int average {total / 10 }; cout << ”n Total of all 10 grades is “ << total; cout << “n Class average is “ << average; © 1992 -2014 by Pearson Education, Inc. All Rights Reserved.
Formulating Algorithms: Sentinel. Controlled Repetition Let’s generalize the class average problem. ◦ Develop a class average program that processes grades for an arbitrary number of students each time it’s run. The program must process an arbitrary number of grades. ◦ How can the program determine when to stop the input of grades? Can use a special value called a sentinel value (also called a signal value, a dummy value or a flag value) to indicate “end of data entry. ” Sentinel-controlled repetition is often called indefinite repetition ◦ the number of repetitions is not known in advance. The sentinel value must not be an acceptable input value. © 1992 -2014 by Pearson Education, Inc. All Rights Reserved.
Formulating Algorithms: Sentinel. Controlled Repetition (cont. ) We approach the class average program with a technique called top-down, stepwise refinement, a technique that is helpful to the development of well-structured programs. We begin with a pseudocode representation of the top—a single statement that conveys the overall function of the program: ◦ Determine the class average for the quiz for an arbitrary number of students The top is, in effect, a complete representation of a program. ◦ Rarely conveys sufficient detail from which to write a pro-gram. © 1992 -2014 by Pearson Education, Inc. All Rights Reserved.
Formulating Algorithms: Sentinel. Controlled Repetition (cont. ) We divide the top into a series of smaller tasks and list these in the order in which they need to be performed. This results in the following first refinement. Initialize variables Input, sum and count the quiz grades Calculate and print the total of all student grades and the class average This refinement uses only the sequence structure— these steps execute in order. © 1992 -2014 by Pearson Education, Inc. All Rights Reserved.
Formulating Algorithms: Sentinel. Controlled Repetition (cont. ) In the second refinement, we commit to specific variables. Initialize variables should become something like: Initialize total to zero Initialize counter to zero The pseudocode statement Input, sum and count the quiz grades requires a repetition statement (i. e. , a loop) that successively inputs each grade. © 1992 -2014 by Pearson Education, Inc. All Rights Reserved.
Formulating Algorithms: Sentinel. Controlled Repetition (cont. ) We don’t know in advance how many grades are to be processed, so we’ll use sentinel-controlled repetition. The user enters legitimate grades one at a time. After entering the last legitimate grade, the user enters the sentinel value. The program tests for the sentinel value after each grade is input and terminates the loop when the user enters the sentinel value. © 1992 -2014 by Pearson Education, Inc. All Rights Reserved.
Formulating Algorithms: Sentinel. Controlled Repetition (cont. ) The second refinement of the preceding pseudocode statement is then Prompt the user to enter the first grade Input the first grade (possibly the sentinel) While the user has not yet entered the sentinel Add this grade into the running total Add one to the grade counter Prompt the user to enter the next grade Input the next grade (possibly the sentinel) © 1992 -2014 by Pearson Education, Inc. All Rights Reserved.
Formulating Algorithms: Sentinel. Controlled Repetition (cont. ) The pseudocode statement Calculate and print the total of all student grades and the class average can be refined as follows: If the counter is not equal to zero Set the average to the total divided by the counter Print the total of the grades for all students in the class Print the class average Else Print “No grades were entered” Test for the possibility of division by zero ◦ Normally a fatal logic error that, if undetected, would cause the program to fail (often called “crashing”). © 1992 -2014 by Pearson Education, Inc. All Rights Reserved.
#include <iostream> #include <iomanip> using namespace std; int main() { int total {0}; unsigned int grade. Counter{0}; cout << “enter grade or -1 to quit”; int grade; int highest = 0; cin >> grade; while (grade != -1) { if ( grade > highest) // Finds the highest grade entered highest = grade; total = total + grade; grade. Counter = grade. Counter + 1; cout << “enter grade or -1 to quit”; cin >> grade; } / end of while loop cout << “The highest grade is “ << highest << endl; © 1992 -2014 by Pearson Education, Inc. All Rights Reserved.
if (grade. Counter != 0) { double average {static_cast<double> (total)/grade. Counter }; cout << “n. Total of the “ << grade. Counter << “grades entered is “ << total; cout << setprecision(2) << fixed; cout << “n. Class average is “ << average << endl; } else cout << “No grades entered”<< endl; } // end of program © 1992 -2014 by Pearson Education, Inc. All Rights Reserved.
Formulating Algorithms: Nested Control Statements Consider the following problem statement: ◦ A college offers a course that prepares students for the state licensing exam for real estate brokers. Last year, ten of the students who completed this course took the exam. The college wants to know how well its students did on the exam. If eight or more passed the instructor gets a bonus. ◦ You’ve been asked to write a program to summarize the results. You’ve been given a list of these 10 students. Next to each name is written a 1 if the student passed the exam or a 2 if the student failed. © 1992 -2014 by Pearson Education, Inc. All Rights Reserved.
Your program should analyze the results of the exam as follows: 1. Display the prompting message “Enter result” each time the program requests another test result. Input each test result (i. e. , a 1 or a 2). 2. Count the number of test results of each type. 3. Display a summary of the test results indicating the number of students who passed and the number who failed. 4. If more than eight students passed the exam, print the message “Bonus to instructor!” © 1992 -2014 by Pearson Education, Inc. All Rights Reserved.
Formulating Algorithms: Nested Control Statements (cont. ) After reading the problem statement carefully, we make the following observations: ◦ Must process test results for 10 students. A counter-controlled loop can be used because the number of test results is known in advance. ◦ Each test result is a number—either a 1 or a 2. Each time the program reads a test result, the program must determine whether the number is a 1 or a 2. For simplicity, we test only for a 1 in our algorithm. If the number is not a 1, we assume that it’s a 2. ◦ Two counters keep track of the exam results—one to count the number of students who passed and one to count the number of students who failed. ◦ After the program has processed all the results, it must decide whether more than eight students passed the exam. © 1992 -2014 by Pearson Education, Inc. All Rights Reserved.
Formulating Algorithms: Nested Control Statements (cont. ) Pseudocode representation of the top: Analyze exam results and decide whether instructor should receive a bonus Once again, it’s important to emphasize that the top is a complete representation of the program, but several refinements are likely to be needed before the pseudocode evolves naturally into a C++ program. Our first refinement is Initialize variables Input the 10 exam results, and count passes and failures Print a summary of the exam results and decide if tuition should be raised Further refinement is necessary. © 1992 -2014 by Pearson Education, Inc. All Rights Reserved.
Formulating Algorithms: Nested Control Statements (cont. ) Counters are needed to record the passes and failures, a counter will be used to control the looping process and a variable is needed to store the user input. The pseudocode statement Initialize variables can be refined as follows: Initialize passes to zero Initialize failures to zero Initialize student counter to one © 1992 -2014 by Pearson Education, Inc. All Rights Reserved.
Formulating Algorithms: Nested Control Statements (cont. ) The following pseudocode statement requires a loop that successively inputs the result of each exam Input the 10 exam results, and count passes and failures 10 exam results, so counter-controlled looping is appropriate. Nested inside the loop, an if…else statement will determine whether each exam result is a pass or a failure and will increment the appropriate counter. The refinement of the preceding pseudocode statement is then While student counter is less than or equal to 10 Prompt the user to enter the next exam result Input the next exam result If the student passed Add one to passes Else Add one to failures Add one to student counter © 1992 -2014 by Pearson Education, Inc. All Rights Reserved.
Formulating Algorithms: Nested Control Statements (cont. ) The pseudocode statement Print a summary of the exam results and decide whether or ot the instructor should receive a bonus can be refined as follows: Print the number of passes Print the number of failures If more than eight students passed Print “Bonus to instructor!” The complete second refinement appears in Fig. 4. 15. © 1992 -2014 by Pearson Education, Inc. All Rights Reserved.
© 1992 -2014 by Pearson Education, Inc. All Rights Reserved.
p. 134 Fig. 4, 14
© 1992 -2014 by Pearson Education, Inc. All Rights Reserved.
C++11 List Initialization C++11 introduces a new variable initialization syntax. List initialization (also called uniform initialization) enables you to use one syntax to initialize a variable of any type. unsigned int student. Counter = 1; In C++11, you can write this as unsigned int student. Counter = { 1 }; or unsigned int student. Counter{ 1 }; © 1992 -2014 by Pearson Education, Inc. All Rights Reserved.
The braces ({ and }) represent the list initializer. For a fundamental-type variable, you place only one value in the list initializer. For an object, the list initializer can be a commaseparated list of values that are passed to the object’s constructor. © 1992 -2014 by Pearson Education, Inc. All Rights Reserved.
For fundamental-type variables, list-initialization syntax also prevents so-called narrowing conversions that could result in data loss. For example, previously you could write int x = 12. 7; which attempts to assign the double value 12. 7 to the int variable x. A double value is converted to an int, by truncating the floating-point part (. 7), which results in a loss of information—a narrowing conversion. © 1992 -2014 by Pearson Education, Inc. All Rights Reserved.
The actual value assigned to x is 12. Many compilers generate a warning for this statement, but still allow it to compile. However, using list initialization, as in int x = { 12. 7 }; or int x{ 12. 7 }; yields a compilation error, thus helping you avoid a potentially subtle logic error. For example, Apple’s Xcode LLVM compiler gives the error Type 'double' cannot be narrowed to 'int' in initializer list © 1992 -2014 by Pearson Education, Inc. All Rights Reserved.
- Slides: 62