Chapter 4. Making Decisions
4.1 Relational Operators Relational operators allow you to compare numeric values and determine if one is greater than, less than, equal to, or not equal to another.
Table 4-1
Table 4-2
The Value of a Relationship Relational expressions are boolean Warning! The equality operator is two equal signs together ==
Table 4-3
Program 4-1 // This program displays the values of true and false // states. #include <iostream.h> void main(void) { int True, False, X = 5, Y = 10; True = X < Y; False = Y == X; cout << "True is " << True << endl; cout << "False is " << False << endl; } Program Output True is 1 False is 0
Table 4-4
4.2 The if Statement The if statement can cause other statements to execute only under certain conditions.
Program 4-2 // This program averages 3 test scores #include <iostream.h> void main(void) { int Score1, Score2, Score3; float Average; cout << "Enter 3 test scores and I will average them: "; cin >> Score1 >> Score2 >> Score3; Average = (Score1 + Score2 + Score3) / 3.0; cout.precision(1); cout.setf(ios::showpoint | ios::fixed); cout << "Your average is " << Average << endl; if (Average > 95) cout << "Congratulations! That's a high score!\n"; }
Program Output with Example Input Enter 3 test scores and I will average them: 80 90 70 [Enter] Your average is 80.0 Program Output with Other Example Input Enter 3 test scores and I will average them: 100 100 100 [Enter] Your average is 100.0 Congratulations! That's a high score!
Table 4-5
Be Careful With Semicolons if (expression) statement; Notice that the semicolon comes after the statement that gets executed if the expression is true; the semicolon does NOT follow the expression
Program 4-3 // This program demonstrates how a misplaced semicolon // prematurely terminates an if statement. #include <iostream.h> void main(void) { int X = 0, Y = 10; cout << "X is " << X << " and Y is " << Y << endl; if (X > Y); cout << "X is greater than Y\n"; } Program Output X is 0 and Y is 10 X is greater than Y
Programming Style and the if Statement The conditionally executed statement should appear on the line after the if statement. The conditionally executed statement should be indented one “level” from the if statement. Note: Each time you press the tab key, you are indenting one level.
Comparing Floating Point Numbers Round-off errors can cause problems when comparing floating point numbers with the equality operator (==)
Program 4-4
And Now Back to Truth When a relational expression is true, it has the value 1. When a relational expression is false it has the value 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.
Not All Operators Are “Equal” Consider the following statement: if (X = 2) cout << “It is True!”; This statement does not determine if X is equal to 2, it makes X equal to 2, therefore, this expression will always be true because the value of the expression is 2, a non-zero value
4.3 Flags A flag is a variable, usually a boolean or an integer, that signals when a condition exists. If your compiler does not support the bool data type, use int instead.
Program 4-6
4.4 Expanding the if Statement The if statement can conditionally execute a block of statement enclosed in braces. if (expression) { statement; // Place as many statements here as necessary. }
Program 4-7 // This program averages 3 test scores. // It uses the variable HighScore as a flag. #include <iostream.h> void main(void) { int Score1, Score2, Score3; float Average; bool HighScore = false; cout << "Enter 3 test scores and I will average them: "; cin >> Score1 >> Score2 >> Score3; Average = (Score1 + Score2 + Score3) / 3.0; if (Average > 95) HighScore = true; // Set the flag variable
Program continues cout.precision(1); cout.setf(ios::showpoint | ios::fixed); cout << "Your average is " << Average << endl; if (HighScore) { cout << "Congratulations!\n"; cout << "That's a high score.\n"; cout << "You deserve a pat on the back!\n"; }
Program Output with Example Input Enter your 3 test scores and I will average them: 100 100 100 [Enter] Your average is 100.0 Congratulations! That's a high score. You deserve a pat on the back! Program Output with Different Example Input Enter your 3 test scores and I will average them: 80 90 70 [Enter] Your average is 80.0
Don’t Forget the Braces! If you intend to execute a block of statements with an if statement, don’t forget the braces. Without the braces, the if statement only executes the very next statement.
4.5 The if/else Statement The if/else statement will execute one group of statements if the expression is true, or another group if the expression is false. If (expression) statement or block of statements; else
Program 4-9 // This program uses the modulus operator to determine // if a number is odd or even. If the number is evenly divided // by 2, it is an even number. A remainder indicates it is odd. #include <iostream.h> void main(void) { int Number; cout << "Enter an integer and I will tell you if it\n"; cout << "is odd or even. "; cin >> Number; if (Number % 2 == 0) cout << Number << " is even.\n"; else cout << Number << " is odd.\n"; }
Program Output with Example Input Enter an integer and I will tell you if it is odd or even. 17 [Enter] 17 is odd.
Program 4-10 // This program asks the user for two numbers, Num1 and Num2. // Num1 is divided by Num2 and the result is displayed. // Before the division operation, however, Num2 is tested // for the value 0. If it contains 0, the division does not // take place. #include <iostream.h> void main(void) { float Num1, Num2, Quotient; cout << "Enter a number: "; cin >> Num1; cout << "Enter another number: "; cin >> Num2;
Program continues if (Num2 == 0) { cout << "Division by zero is not possible.\n"; cout << "Please run the program again and enter\n"; cout << "a number besides zero.\n"; } else Quotient = Num1 / Num2; cout << "The quotient of " << Num1 << " divided by "; cout << Num2 << " is " << Quotient << ".\n";
Program Output (When the user enters 0 for Num2) Enter a number: 10 [Enter] Enter another number: 0 [Enter] Division by zero is not possible. Please run the program again and enter a number besides zero.
4.6 The if/else if Construct The if/else if statement is a chain of if statements. The perform their tests, one after the other, until one of them is found to be true. If (expression) statement or block of statements; else if (expression) // put as many else it’s as needed here
Program 4-11 // This program uses an if/else if statement to assign a // letter grade (A, B, C, D, or F) to a numeric test score. #include <iostream.h> void main(void) { int TestScore; char Grade; cout << "Enter your numeric test score and I will\n"; cout << "tell you the letter grade you earned: "; cin >> TestScore;
Program Continues if (TestScore < 60) Grade = 'F'; else if (TestScore < 70) Grade = 'D'; else if (TestScore < 80) Grade = 'C'; else if (TestScore < 90) Grade = 'B'; else if (TestScore <= 100) Grade = 'A'; cout << "Your grade is " << Grade << ".\n"; }
Program Output with Example Input Enter your test score and I will tell you the letter grade you earned: 88 [Enter] Your grade is B.
Program 4-12 // This program uses independent if/else statements to assign a // letter grade (A, B, C, D, or F) to a numeric test score. // Do you think it will work? #include <iostream.h> void main(void) { int TestScore; char Grade; cout << "Enter your test score and I will tell you\n"; cout << "the letter grade you earned: "; cin >> TestScore;
Program Continues if (TestScore < 60) Grade = 'F'; if (TestScore < 70) Grade = 'D'; if (TestScore < 80) Grade = 'C'; if (TestScore < 90) Grade = 'B'; if (TestScore <= 100) Grade = 'A'; cout << "Your grade is " << Grade << ".\n"; }
Program Output with Example Input Enter your test score and I will tell you the letter grade you earned: 40 [Enter] Your grade is A.
4.7 Using a Trailing else A trailing else, placed at the end of an if/else if statement, provides default action when none of the if’s have true expressions
Program 4-14 // This program uses an if/else if statement to assign a // letter grade (A, B, C, D, or F) to a numeric test score. // A trailing else has been added to catch test scores > 100. #include <iostream.h> void main(void) { int TestScore; cout << "Enter your test score and I will tell you\n"; cout << "the letter grade you earned: "; cin >> TestScore;
Program continues if (TestScore < 60) { cout << "Your grade is F.\n"; cout << "This is a failing grade. Better see your "; cout << "instructor.\n"; } else if (TestScore < 70) cout << "Your grade is D.\n"; cout << "This is below average. You should get "; cout << "tutoring.\n";
Program continues else if (TestScore < 80) { cout << "Your grade is C.\n"; cout << "This is average.\n"; } else if (TestScore < 90) cout << "Your grade is B.\n"; cout << "This is an above average grade.\n";
Program continues else if (TestScore <= 100) { cout << "Your grade is A.\n"; cout << "This is a superior grade. Good work!\n"; } else cout << TestScore << " is an invalid score.\n"; cout << "Please enter scores no greater than 100.\n";
Program Output with Example Input Enter your test score and I will tell you the letter grade you earned: 104 [Enter] 104 is an invalid score. Please enter scores no greater than 100.
4.8 Focus on Software Engineering: Menus You can use the if/else if statement to create menu-driven programs. A menu-driven program allows the user to determine the course of action by selecting it from a list of actions.
Program 4-15 // This program displays a menu and asks the user to make a // selection. An if/else if statement determines which item // the user has chosen. #include <iostream.h> void main(void) { int Choice, Months; float Charges; cout << "\t\tHealth Club Membership Menu\n\n"; cout << "1. Standard Adult Membership\n"; cout << "2. Child Membership\n"; cout << "3. Senior Citizen Membership\n"; cout << "4. Quit the Program\n\n";
cout << "Enter your choice: "; cin >> Choice; Program continues cout << "Enter your choice: "; cin >> Choice; cout.setf(ios::fixed | ios::showpoint); cout.precision(2); if (Choice == 1) { cout << "\nFor how many months? "; cin >> Months; Charges = Months * 40.00; cout << "The total charges are $" << Charges << endl; }
Program continues else if (Choice == 2) { cout << "\nFor how many months? "; cin >> Months; Charges = Months * 20.00; cout << "The total charges are $" << Charges << endl; } else if (Choice == 3) Charges = Months * 30.00;
cout << "The valid choices are 1 through 4. Run the\n"; Program continues else if (Choice != 4) { cout << "The valid choices are 1 through 4. Run the\n"; cout << "program again and select one of those.\n"; }
Program Output with Example Input Health Club Membership Menu 1. Standard Adult Membership 2. Child Membership 3. Senior Citizen Membership 4. Quit the Program Enter your choice: 3 [Enter] For how many months? 6 [Enter] The total charges are $180.00
4.9 Focus on Software Engineering: Nested if Statements A nested if statement is an if statement in the conditionally-executed code of another if statement.
Program 4-16 // This program demonstrates the nested if statement. #include <iostream.h> void main(void) { char Employed, RecentGrad; cout << "Answer the following questions\n"; cout << "with either Y for Yes or "; cout << "N for No.\n"; cout << "Are you employed? "; cin >> Employed; cout << "Have you graduated from college "; cout << "in the past two years? "; cin >> RecentGrad;
Program continues if (Employed == 'Y') { if (RecentGrad == 'Y') cout << "You qualify for the special "; cout << "interest rate.\n"; }
Program Output with Example Input Answer the following questions with either Y for Yes or N for No. Are you employed? Y Have you graduated from college in the past two years? Y You qualify for the special interest rate.
Program Output with Other Example Input Answer the following questions with either Y for Yes or N for No. Are you employed? Y Have you graduated from college in the past two years? N
4.10 Logical Operators Logical operators connect two or more relational expressions into one, or reverse the logic of an expression.
Table 4-6
Table 4-7
Program 4-18 // This program demonstrates the && logical operator. #include <iostream.h> void main(void) { char Employed, RecentGrad; cout << "Answer the following questions\n"; cout << "with either Y for Yes or "; cout << "N for No.\n"; cout << "Are you employed? "; cin >> Employed;
Program continues cout << "Have you graduated from college "; cout << "in the past two years? "; cin >> RecentGrad; if (Employed == 'Y'&& RecentGrad == 'Y') { cout << "You qualify for the special "; cout << "interest rate.\n"; } else cout << "You must be employed and have \n"; cout << "graduated from college in the\n"; cout << "past two years to qualify.\n";
Program Output with Example Input Answer the following questions with either Y for Yes or N for No. Are you employed? Y Have you graduated from college in the past two years? N You must be employed and have graduated from college in the past two years to qualify.
Table 4-8
Program 4-19 // This program asks the user for their annual income and // the number of years they have been employed at their current // job. The || operator is used in a if statement that // determines if the income is at least $35,000 or their time // on the job is more than 5 years. #include <iostream.h> void main(void) { float Income; int Years;
Program continues cout << "What is your annual income? "; cin >> Income; cout << "How many years have you worked at " << "your current job? "; cin >> Years; if (Income >= 35000 || Years > 5) cout << "You qualify.\n"; else { cout << "You must earn at least $35,000 or have\n"; cout << "been employed for more than 5 years.\n"; }
Program Output with Example Input What is your annual income? 40000 [Enter] How many years have you worked at your current job? 2 [Enter] You qualify. Program Output with Example Input What is your annual income? 20000 [Enter] How many years have you worked at your current job? 7 [Enter]
Table 4-9
Program 4-20 #include <iostream.h> void main(void) { float Income; int Years; cout << "What is your annual income? "; cin >> Income; cout << "How many years have you worked at " << "your current job? "; cin >> Years; if (!(Income >= 35000 || Years > 5)) cout << "You must earn at least $35,000 or have\n"; cout << "been employed for more than 5 years.\n"; } else cout << "You qualify.\n";
Precedence of Logical Operators ! && ||
4.11 Checking Numeric Ranges With Logical Operators Logical operators are effective for determining if a number is in or out of a range.
4.12 Focus on Software Engineering: Validating User Input As long as the user of a program enters bad input, the program will produce bad output. Program should be written to filter out bad input.
Examples of validation: Numbers are check to ensure they are within a range of possible values. Values are check for their “reasonableness”. Items selected from a menu or other set of choices are check to ensure they are available options. Variables are check for values that might cause problems, such as division by zero.
4.13 More About Variable Declarations and Scope The scope of a variable is limited to the block in which is is declared. Variables declared inside a set of braces have local scope or block scope.
Program 4-22A #include <iostream.h> void main(void) { cout << "What is your annual income? "; float Income; cin >> Income; cout << "How many years have you worked at " << "your current job? "; int Years; cin >> Years; if (Income >= 35000 || Years > 5) cout << "You qualify.\n"; else cout << "You must earn at least $35,000 or have\n"; cout << "been employed for more than 5 years.\n"; }
Program 4-22B #include <iostream.h> void main(void) { cout << "What is your annual income? "; float Income; cin >> Income; cout << "How many years have you worked at " << "your current job? "; int Years; cin >> Years; if (Income >= 35000 || Years > 5) cout << "You qualify.\n"; else cout << "You must earn at least $35,000 or have\n"; cout << "been employed for more than 5 years.\n"; }
Program 4-22C #include <iostream.h> void main(void) { cout << "What is your annual income? "; float Income; cin >> Income; int Years; cout << "How many years have you worked at " << "your current job? "; cin >> Years; if (Income >= 35000 || Years > 5) cout << "You qualify.\n"; else cout << "You must earn at least $35,000 or have\n"; cout << "been employed for more than 5 years.\n"; }
Program 4-23 // This program demonstrates a variable declared in an inner block. #include <iostream.h> void main(void) { cout << "What is your annual income? "; float Income; cin >> Income; if (Income >= 35000) int Years; cout << "How many years have you worked at " << "your current job? "; cin >> Years; if (Years > 5) cout << "You qualify.\n";
Program continues else { cout << "You must have been employed for\n"; cout << "more than 5 years to qualify.\n"; } cout << "You must earn at least $35,000 to\n"; cout << "qualify.\n";
Variables With the Same Name When a block is nested inside another block, a variable declared in the inner block may have the same name as a variable declared in the outer block. The variable in the inner block takes precedence over the variable in the outer block.
Program 4-24 // This program uses two variables with the name Number. #include <iostream.h> void main(void) { int Number; cout << "Enter a number greater than 0: "; cin >> Number; if (Number > 0)
cout << "Now enter another number: "; cin >> Number; Program continues cout << "Now enter another number: "; cin >> Number; cout << "The second number you entered was "; cout << Number << endl; } cout << "Your first number was " << Number << endl;
Program Output with Example Input Enter a number greater than 0: 2 [Enter] Now enter another number: 7[Enter] The second number you entered was 7 Your first number was 2
4.14 Comparing Strings You cannot compare strings using the relational operators. The strcmp library function is used instead.
Program 4-25 // This program illustrates that you cannot compare strings // with relational operators. Although it appears to test the // strings for equality, that is NOT what happens. #include <iostream.h> void main(void) { char FirstString[40], SecondString[40]; cout << "Enter a string: "; cin.getline(FirstString, 40); cout << "Enter another string: "; cin.getline(SecondString, 40); if (FirstString == SecondString) cout << "You entered the same string twice.\n"; else cout << "The strings are not the same.\n"; }
Program Output with Example Input Enter a string: Alfonso [Enter] Enter another string: Alfonso [Enter] The strings are not the same.
The strcmp Function strcmp(string1, string2); //include string.h to use this function If the two strings are identical, strcmp returns 0. If string2 is alphabetically higher (on the ASCII chart) than string1, strcmp returns a negative number. If string2 is alphabetically lower (on the ASCII chart) than string1, strcmp returns a positive number.
Program 4-26 #include <iostream.h> #include <string.h> void main(void) { char FirstString[40], SecondString[40]; cout << "Enter a string: "; cin.getline(FirstString, 40); cout << "Enter another string: "; cin.getline(SecondString, 40); if (strcmp(FirstString, SecondString) == 0) cout << "You entered the same string twice.\n"; else cout << "The strings are not the same.\n"; }
Program 4-27 // This program uses strcmp to compare the sting entered // by the user with the valid stereo part numbers. #include <iostream.h> #include <string.h> void main(void) { const float Aprice = 249.0, Bprice = 299.0; char PartNum[8]; cout << "The stereo part numbers are:\n"; cout << "\tBoom Box, part number S147-29A\n";
Program continues cout << "\tShelf Model, part number S147-29B\n"; cout << "Enter the part number of the stereo you\n"; cout << "wish to purchase: "; cin.width(9); // So they won't enter more than 8 char's cin >> PartNum; cout.setf(ios::fixed || ios::showpoint); cout.precision(2); if (strcmp(PartNum, "S147-29A") == 0) cout << "The price is $" << Aprice << endl; else if (strcmp(PartNum, "S147-29B") == 0) cout << "The price is $" << Bprice << endl; else cout << PartNum << " is not a valid part number.\n"; }
Program Output with Example Input The stereo part numbers are: Boom Box, part number S14729A Shelf Model, part number S147-29B Enter the part number of the stereo you wish to purchase: S147-29B [Enter] The price is $299.00
Program 4-28 // This program uses the return value of strcmp to alphabetically // sort two strings entered by the user. #include <iostream.h> #include <string.h> void main(void) { char Name1[30], Name2[30]; cout << "Enter a name (last name first): "; cin.getline(Name1, 30); cout << "Enter another name: "; cin.getline(Name2, 30);
cout << "Here are the names sorted alphabetically:\n"; Program continues cout << "Here are the names sorted alphabetically:\n"; if (strcmp(Name1, Name2) < 0) cout << Name1 << endl << Name2 << endl; else if (strcmp(Name1, Name2) > 0) cout << Name2 << endl << Name1 << endl; else cout << "You entered the same name twice!\n"; }
Program Output with Example Input Enter a name (last name first): Smith, Richard [Enter] Enter another name: Jones, John [Enter] Here are the names sorted alphabetically Jones, John Smith, Richard
4.15 The Conditional Operator You can use the conditional operator to create short expressions that work like if/else statements expression ? result if true : result if false;
Program 4-29 // This program calculates a consultant's charges at $50 per hour, for a // minimum of 5 hours. The ?: operator adjusts Hours to 5 if less than 5 // hours were worked. #include <iostream.h> void main(void) { const float PayRate = 50.0; float Hours, Charges; cout << "How many hours were worked? "; cin >> Hours; Hours = Hours < 5 ? 5 : Hours; Charges = PayRate * Hours; cout.precision(2); cout.setf(ios::fixed | ios::showpoint); cout << "The charges are $" << Charges << endl; }
Program Output with Example Input How many hours were worked? 10 [Enter] The charges are $500.00 Program Output with Example Input How many hours were worked? 2 [Enter] The charges are $250.00
Program 4-30 // This program uses the return value of strcmp to alphabetically // sort two strings entered by the user. #include <iostream.h> #include <string.h> void main(void) { char Name1[30], Name2[30]; cout << "Enter a name (last name first): "; cin.getline(Name1, 30);
cout << "Enter another name: "; cin.getline(Name2, 30); Program continues cout << "Enter another name: "; cin.getline(Name2, 30); cout << "Here are the names sorted alphabetically:\n"; cout << (strcmp(Name1, Name2) <= 0 ? Name1 : Name2) << endl; cout << (strcmp(Name1, Name2) > 0 ? Name1 : Name2) << endl; }
Program Output with Example Input Enter a name (last name first): Smith, Richard [Enter] Enter another name: Jones, John [Enter] Here are the names sorted alphabetically Jones, John Smith, Richard
4.16 The switch Statement The switch statement lets the value of a variable or expression determine where the program will branch to.
Program 4-31 // The switch statement in this program tells the user something // he or she already knows: what they just entered! #include <iostream.h> void main(void) { char Choice; cout << "Enter A, B, or C: "; cin >> Choice;
Program continues switch (Choice) { case 'A': cout << "You entered A.\n"; break; case 'B': cout << "You entered B.\n"; case 'C': cout << "You entered C.\n"; default: cout << "You did not enter A, B, or C!\n"; }
Program Output with Example Input Enter A, B, or C: B [Enter] You entered B. Program Output with Different Example Input Enter a A, B, or C: F [Enter] You did not enter A, B, or C!
Program 4-32 // The switch statement in this program tells the user something // he or she already knows: what they just entered! #include <iostream.h> void main(void) { char Choice; cout << "Enter A, B, or C: "; cin >> Choice;
case 'A': cout << "You entered A.\n"; Program continues switch (Choice) { case 'A': cout << "You entered A.\n"; case 'B': cout << "You entered B.\n"; case 'C': cout << "You entered C.\n"; default: cout << "You did not enter A, B, or C!\n"; }
Program Output with Example Input Enter a A, B, or C: A [Enter] You entered A. You entered B. You entered C. You did not enter A, B, or C! Program Output with Example Input Enter a A, B, or C: C [Enter]
Program 4-33 // This program is carefully constructed to use the "fallthrough" // feature of the switch statement. #include <iostream.h> void main(void) { int ModelNum; cout << "Our TVs come in three models:\n"; cout << "The 100, 200, and 300. Which do you want? "; cin >> ModelNum; cout << "That model has the following features:\n";
case 300:cout << "\tPicture-in-a-picture.\n"; Program continues switch (ModelNum) { case 300:cout << "\tPicture-in-a-picture.\n"; case 200:cout << "\tStereo sound.\n"; case 100:cout << "\tRemote control.\n"; break; default:cout << "You can only choose the 100,"; cout << "200, or 300.\n"; }
Program Output with Example Input Our TVs come in three models: The 100, 200, and 300. Which do you want? 100 [Enter] That model has the following features: Remote control. Program Output with Example Input The 100, 200, and 300. Which do you want? 200 [Enter] That model has the following features: Stereo sound. Remote control.
Program 4-34 // The switch statement in this program uses the "fallthrough" // feature to catch both upper and lowercase letters entered // by the user. #include <iostream.h> void main(void) { char FeedGrade; cout << "Our dog food is available in three grades:\n"; cout << "A, B, and C. Which do you want pricing for? "; cin >> FeedGrade;
Program continues switch(FeedGrade) { case 'a': case 'A': cout << "30 cents per pound.\n"; break; case 'b': case 'B': cout << "20 cents per pound.\n"; case 'c': case 'C': cout << "15 cents per pound.\n"; default: cout << "That is an invalid choice.\n"; }