This document contains review questions and exercises about decision making structures in C++ such as if/else statements, logical operators, and switch statements. It includes multiple choice, fill-in-the-blank, true/false, coding, and error finding questions. The goal is to test the reader's understanding of conditional logic and how to implement decision making in programs.
This document contains review questions and exercises about decision making structures in C++ such as if/else statements, logical operators, and switch statements. It includes multiple choice, fill-in-the-blank, true/false, coding, and error finding questions. The goal is to test the reader's understanding of conditional logic and how to implement decision making in programs.
Short Answer 1. Describe the dIfference between the if/else if statement and a series of if statements. 2. In an if /else if statement, what is the purpose of a trailing else? 3. What is a flag and how does it work? 4. Can an if statement test expressions other than relational expressions? Explain. 5. Briefly describe how the && operator works. 6. Briefly describe how the I \ operator works. 7. Why are the relational operators called relational? 8. Why do most programmers indent the conditionally executed statements in a decision structure? FIII-in-the-Blank 9. An expression using the greareNhan, less-than, greater-than-or-equal to, less-than-or- equal -ro, equal, o r not-equal to operator is called a(n) expression. 10. A relational expression is either ____ or ___ _ 11. The value of a relational expression is 0 jf the expression is _ ____ or 1 if the expression IS ___ _ _ 12. The if statement regards an expression with the value 0 as ____ _ 13. The i f statemenr regards an expression with a nonzero value as ____ _ 14. For an if statement to conditionally execute a group of statements, the statements must be enclosed in a sec of ___ _ 15. In an if/e lse sratement, the if part executes its statement or block if the expression IS , and the else part executes its statement or block if the expression is 16. The [railing else in an if/else if Statement has a similar purpose as the _____ section of a switch statement. 17. The if/else if statement is actually a form of the _____ if statement. 18. If the sub-expression on the left of the ____ logical operator is false, the right sub-expression is not checked. 19. If the sub-expression on the left of the ____ logical operator is true, the fight sub-expression is not checked. 20. The _ ____ Iogical operator has higher precedence than the other logical operators. 21. The logical operators have _____ assOClatlvlty. 22. The ~ __ logical operato! works best when resting a number to determine if it is within a range. 23. The logical operator works best when tesring a number to determine If it is oU[side a range. Review Questions and Exercises 24. A variable with scope is only visible when the program is executing in the block containing the variable's definition. 25. The strcrnp function is used to compare ____ _ 26. An expression using the conditional operator is called a(n) _____ expression. 27. The expression that follows the switch statement must have a{n) _____ value. 28. The expression following a case statement must be a(n) _______ _ 29. A program wi ll "fall through" a case section if it is missing the _____ statement. 30. What value will be stored in the variable t after each of the following statements executes? A} t (12 > I) , ___ _ B) t - 12 < 0), ___ _ qt-IS-- D) t 15 (32))' ___ _ 5)' ___ _ Algorithm Workbench 31. Write an if statement that assigns 100 to x when y is equal to O. 32. Write an if/else srarement that assigns a to x when y is equal to 10. Otherwise it should assign 1 to x. 33. Using the following chart, write an if/else if statement that assigns .10, .15, or .20 to corrunission, depending on the value in sales. Sales Up to $10,000 $10,000 to $15,000 Over $15,000 Commission Rate 10% 15% 20% 34. Write an if statement that sets the variable hours to 10 when rhe flag variable minimum is set . 35. Write nested if statements that perform the following tests: If arnountl is greater than 10 and amount2 is less than 100, display the greater of the two. 36. Write an if statement that prints the message "The number is valid" if the variable grade is within the range 0 through 100. 37. Write an if statement that prints the message "The number is valid" if the variable temperature is within rhe range -50 through IS0. 38. Write an if statement that prints the message "The number is not valid" if the vari able hours is outside the range 0 through 80. 39. Write an if/else statement that displays the strings in the arrays titlel and title2 in alphabetical order. 40. Convert the following if/else if statement into a switch statement: if (choice -- 1) cout fixed showpoint setprecision(2) ; 233 234 Chapter 4 Making Decisions } else if (choice ~ 2 I I choice ~ 3) { cout fixed showpoint setprecision(4); } else if (choice == 4) ( cout fixed showpoint setprecision(6); } else { cout fixed showpoint setprecision(8)i } 41. Match the conditional expression with the if le1se statement that performs the same operation. AI q x BI q = x C) x < y < y ? a + b < y ? x 2 ? q = 0 q = if Ix < y) q 0, else q = " if (x < y) q .. a + bi else q "'" x 2, U(x<y) q ::0 X .. 2; else q "" a -+ bi x 2 , a + b, l' , True or False 42. T F 43. T F 44. T F 45. T F 46. T F 47. T F 48. T F The"" operator and the "'= operator perform the same operation. A variable defined in an inner block may not have the same name as a vari- able defined in the outer block. A conditionally executed statement should be indented one level from the i f Statement. All lines in a block should be indented one level. It's safe to assume that all uninitialized variables automatically start with 0 as their value. When an if statement is nested in the if part of another statement) t he only time the inner if is executed is when the expression of the outer if is true. When an if statement is nested in the else part of another statement) as in an if/e lse if, t he only t ime the inner if is executed is when the expression of the outer if is true. Review Questions and Exercises 49. T F The scope of a variable is limited ro the block in which it is defined. 50. T F Stri ngs may be direcrly compared by using the == operator. 51. T F x != y is the same as (x> y I I x < y) 52. T F y < x is t he same as x >= y 53. T F x >= y is the same as (x> y " X = y) Assume the variabl.es x .. 5, 'i ;;. 6, and 7. ;;. S. Indicate by circling the T or F whether each of t he following conditions is true or fa lse: 54. T F x == 5 II y > 3 55. T F 7 <= x " z > 4 56. T F 2 1'" Y && Z 1= 4 57. T F x >= 0 II x <'" y Find the Errors Each of the following programs has errors. Find as many as you can. 58. II Thi s program averages 3 test scores . II It uses the variable perfectScore as a flag . include <iostream> using namespace std; int main() { } cout "Enter your 3 test scores and I will "; "average them:" ; int score1, score2, score3, cin score I score2 score3; double average: average (scorel + score2 + score3) I 3.0; if (average - 100)1 perfectScore = true; II Set the flag variable cout "Your average is " average endl: bool perfectScore; if (perfect5core): { cout "congratulations!\n" : cout "That's a perfect score.\n"; cout .. You deserve a pat on the back! \n" : return 0; 59. II This program divides a user- supplied number by another II user-supplied number . It checks for division by zero . 'include <iostream> using namespace std; int main() { double numl, num2, quotient; cout "Enter a number : " ; cin numl : cout "Enter another number : " ; 235 236 Chapter 4 Making Oecisions ) cin num2i if (num2 "" ... 0) cout "Division by zero is not cout run the program again cout "and enter a number besides zero.\n M ; else quotient numl I num2; cout "The quotient of numl cout M divided by " num2 .. is Hi cout quotient endl; return 0; 60. II This program uses an if/else if statement to assign a to a numeric test Bcore. II letter grade (A, a, 'include <iostream> C, D, or F) using namespace std: int maine 1 ( ) int testScore; cout "Enter your test score and I will tell you\ n"; cout "the letter grade you earned: "; cin t estSco re; if (testScore < 60) cout "Your grade is F.\n"j else if (teatScore < 70) cout "Your grade is D. \ 0"; else if (testScore < 80) cout HYour grade is C.\n": else if (testScore < 90) cout "Your grade is B . \n M ; else cout "That is not a valid score. \n M ; else if (testScore <- 100) cout "Your grade is A. \n" ; return 0; 61 . II This program tests two strings for equality. tinclude <iostream> using nameapace std; int main ( ) ( canst int SIZE - 40; char string1[SIZE). string2{SIZE ); cout a string: "; cin.getline(string1, 80); caut "Enter another l5tr ing: M; cin.getline(string2, 80); if (stringl -- string2) cOut "The strings are the same . \n"; else ) Review Questions and Exercises cout "The strings are not the same.\n"; return 0; 62. II This program uses a switch-case statement to assign a II letter grade (A. B. C. 0, or F) to a numeric test score. 'include <iostream> using namespace std; int main( ) { double testScorej cout "Ente r your test scor e and I will tell you\n"; cout "the letter grade you earned: "; ) cin testScore; switch (testScore) { case case case case (testScore < 60 . 0) : cout "Your grade is F.\n"; break; (testScore < 70.0) : cout "Your grade is D. \n"; break; ltestScore < 80.0) : cout "Your grade is C. \n" ; break ; (testScore < 90 . 0) : cout "Your grade is B. \0" i break; case ltestScore <= 100.0): default : cout "Your grade is A. \n"; break; cout "That score isn't valid\n"; retur n 0; 63. The following statement should determine if x is not greater than 20. What is wrong with it? if ilx > 20) 64. The followIng Statement should deter mine if count is within the ra nge of a through 100. What is wrong wit h it? if (count >- 0 I I count <- 100) 65. The followi ng statement should determine if count is outside the range of 0 through 100. What is wrong with it? i f (count < 0 && count> 100) 66. The following statement should assign 0 to z if a is less than 10, otherwise it should assign 7 to z. What is wrong with it? Z : (a < 10) : 0 ? 7: 2 3 7 238 Chapter 4 Making Decisions Programming Challenges 1. Minimum/ Maximum Write a program (hat asks the user to enter twO numbers. The program should use the conditional operator to determine which number is the smaller and which is the larger. 2. Roman Numeral Converter Write a program that asks the user to enter a number within the range of 1 through 10. Use a switch statement to display the Roman numeral version of that number. Input Validation: Do not accept a number less than 1 or greater than 10. 3. Magic Dates The da te J une la, 1960 is special because when we write it in the following format, the monrb times the day equals the year. 6/10/60 Write a program that asks the user to enter a month (in numeric form), a day, and a two-digit yea,f. The program should then determine whether the month times the day is equal to the year. If so, it should display a message saying the date is magic. Other- wise it should display a message saying the date is not magic. 4. Areas of Rectangles The area of a rectangle is the rectangle's length times its width. Write a program t hat asks for the length and width of two rectangles. The program should tell the user which rectangle has the greater area, or if the areas are the same. 5. Body Mass Index Write a program that calculates and displays a person's body mass index (BMI ). The BMI is often used to determine whet her a person with a sedentary lifestyle is over- weight or underweight for his or her height. A person's BMI is calculated with the fol- lowing formula: BMI = weight x 703 1 height' where weight is measured in pounds and height is measured in inches. The program should display a message indicating whether the person has optimal weight, is under- weight, or is overweight. A sedentary person's weight is considered to be optimal if his or her BMl is between 18.5 and 25. If the BMI is less [han 18.5, the person is consid- ered to be underweight. If the BMl value is greater than 25, the person is considered to be overweight. 6. Mass and Weight Scientists measure an object's mass in ki lograms and its weight in newtons. If you know the amount of mass that an object has, yOll can calculare itS weight, in newtons, wi th rhe followi ng formula: Weight:: mass x 9.8 Solving the Time CalculalOr problem Review Questions and Exercises Write a program rhar asks the user fO enter an object's mass, and then calculates and displays its weight. If the object weighs more than 1,000 newtons, display a message indicating that it is toO heavy. If the object weighs less than 10 newtons, display a message indicating that the object is toO light. 7. Time Calculator Write a program that asks the user fO enter a number of seconds. There are 60 seconds in a minute. If the number of seconds entered by the user is greater than or equal fO 60, the program should display the number of minutes in thar many seconds. There are 3,600 seconds in an hour. If the number of seconds entered by the user is greater than or equal to 3,600, the program should display the number of hours in that many seconds. There are 86,400 seconds in a day. If the number of seconds entered by the user is greater than or equal to 86,400, the program should display the number of days in that many seconds. 8. Sorted Names Write a program that asks the user to cnter three names, and then displays the names sorted in alphabet ica l order. Assume that none of the names are the same. For exam- ple, if the user entered "Charl ie," " Leslie," and" Andy," the program would display: Andy Charlie Leslie 9. Math Tutor This is a modification of Programming Challenge 15 from Chapter 3. Write a pro- gram that can be used as a math tutor for a young student. The program should dis- play two random numbers that are to be added, such as: 247 + 129 The program should wait for the student to enter the answer. If the answer is correct, a message of congrat ulations should be primed. If the answer is incorrect, a message should be printed showing the correct answer. 10. Software Sales A software company sells a package that retails for $99. Quantity discounts are given accordi ng to the following table. Quantity Di scount 10- 19 20% 20-49 30% 50-99 40% 100 or more 50% 23 9 240 Chapter 4 Making Decisions Write a program that asks for the number of units sold and computes the total cost of the purchase. Input Validation: Make SIIre the number of units is greater than O. 11. Book Club Points Serendipity Booksellers has a book club that awards points to its customers based on the number of books purchased each month. The points arc awarded as follows: If a customer purchases 0 books, he or she earns 0 points. If a customer purchases 1 book, he or she earns 5 points. If a customer purchases 2 books, he or she earns 15 points. If a customer purchases 3 books, he Or she earns 30 points. If a customer purchases 4 or more books, he or she earns 60 poims. \Vrite a program that asks the user to enter the number of books that he or she has purchased [his month and then displays the number of points awarded. 12. Bank Charges A bank charges $10 per month plus the following check fees for a commercial check- mg account: $.1 0 each for fewer than 20 checks $.08 each for 20-39 checks $.06 each for 40-59 checks $.04 each for 60 or more checks The bank also charges an extra $15 if the balance of the accOunt falls below $400 (before any check fees are applied). Write a program that asks for the beginning bal - ancc and the number of checks written. Compute and display the bank's service fees for the moneh. InpHt Validation: Do not accept a negative value for the number of checks written. If a Ilegative value is given for the begimlillg balance, display a ll urgent message illdicat ing the account is overdrawn. 13. Shipping Charges The Fast Freight Shipping Company charges the followi ng rates: Weight of Package (in Kilograms ) 2 Kg or less Over 2 Kg but not more than 6 kg Over 6 Kg but not more than 10 kg Over 10 Kg but nor more than 20 kg Race per 500 Miles Shipped $1.10 $2.20 $3.70 $4. 80 Write a program that as ks for the weight of the package and the distance it is to be shipped, and then displays the charges. Input Validation: Do not accept values of 0 or less for the weight of the package, Do not accept weights of more than 20 Kg (this is the maximum weight the company will ship). Do not accept distances of less than 10 miles or more than 3,000 miles. These are the company's minimum and maximJlm shipping distances, Review Questions and Exercises 241 14. Runni ng the Race Write a program rhar asks (or the names of three runners and the rime it rook each of them to finish a race.lhe program should disp\ay who came in nrst, second, and third place. Input Validation: Be sure the names do not overflow the arrays. Only accept positive nllmbers (or the times. 15. Personal Best Write a program thar asks for the name of a pole vaulter and the dates and vault heights (in meter s) of the athlete's three best vatl lrs . It should then report, in order of height (best fi rst), the date on which each vauh was made and its height. Input Validation: Only accept values between 2.0 and 5.0 for the heights. 16. Fat Gram Calculator Write a program thar asks for the number of calories and fat grams in a food. The program should display the percentage of calories that come from faL If the calories from fat are less than 30% of the total calori es of the food, it should also display a message indicating that the food is low in fat . One gram of fat has 9 calories, so Calories from fat = fat grams'" 9 The percentage of calor ies from fat can be calculated as Calories from fat -:- cotal calories Input Validation: Make st/1'e the number of calories and fat grams are nOlless than O. Also, the number of calories from fat cannot be greater thall the total number of calo- ries. If that hap/Jens, display an error message indicatillg that either the calories or fat grams were incorrectly entered. . 17. Spectral Analysis 1 a scientist knows the wavelength of an electromagnetic wave, he or she can determine what type of radiation it is. Write a program that asks for the wavelength of an electro- magnetic wave in meters and then displays what that wave is according co the chart below. (For example, a wave with a wavelength of 1-10 meters would be an X-ray.) 1 x 11}-2 1)( 1(J-3 7x10-7 @__ 18. Tbe Speed of Sound 4)( 10-7 1)( 10""8 I 1)( 10- 11 Gamma Rays The following table shows the approximate speed of sound in air, water, and steel. Medium Air Water Steel Speed 1,100 feet per second 4,900 feet per second 16,400 feet per second 242 Chapter 4 Making Decisions Write a program that displays a menu allowing the L1 ser to select air, water, or steel. After the user has made a selection, he or she should be asked to emer t he distance a sound wave will travel in the selected medium. The program will then display rhe amounr of ti me it wilJ take. (Round the answer to four decimal places.) Input Validation: Check that the user has selected one of the available choices from the menu. Do not accept distances Jess than O. 19. The Speed of Sound in Gases When sound t ravels through a gas, its speed depends primaril y on the density of rhe medium. The less dense the medium, the faster t he speed wi ll be. The following ta ble shows the approximate speed of SOllnd at 0 degrees centigrade, measured in meters per second, when traveling through carbon dioxide, ai r, helium, and hydrogen. Medium Carbon Dioxide Air Helium Hydrogen Speed (Meters per Second) 258.0 331.5 972.0 1,270.0 Write a program that displays a menu allowing the user ro select one of these four gases. After a selecti on has been made, the user should enter the number of seconds it rook for [he sound ro travel in (his medi um from its source to the location at which it was detected. The program should then report how far away (in meters) the source of t he sound was from the detection location. blput Validation: Check that the user has selected 011e of the available menu choices. Do not accept times less than 0 seconds or more than 30 seconds. 20. Freezing and Boiling Points The following table lists the freezing and boiling points of several substances. Write a program that asks the user to enter a temperature, and t hen shows all the substances that will freeze at that temperature and all that wi ll boil at t hat temperature. For example, if the user enters -20 the program should report that water will freeze and oxygen will boil at that temperature. Substance Freezing Point (CF) Boiling Point r F) Ethyl alcohol - 173 172 Mercury -38 676 Oxygen -362 -306 Water 32 212 Revi ew Questions and Exercises 21. Geometry Calculator Write a program that displays the fonowing menu: Geometry calculator 1 . Calculate the Area of a Circle 2. Calculate the Area of a Rectangle J. calculate the Area of a Triangle 4. Quit Enter your choice (1 - 4): If the user enters 1, the program should ask for the radi us of the circle and tben play its area. Use the following formula: Use 3. 14159 for 1t and the radi us of the circle for r. If the user enters 2, the program should ask for the length and width of the rectangle and then display the rectangle's area. Use the following formula: area = length * width If the user enters 3 the program should ask for the length of the triangle's base and its height, and then display its area. Use the following formula: area = base * height * .5 If the user enters 4, the program should end. Input Validation; Display an error message if the user enters a number outside the range of 1 through 4 when selecting an item from the menu. Do not accept 11egative values for the circle's radius, the rectangle's length Dr width. Dr the triangle's base or height. 22. Calls A carrier charges the fo llowing (ates for telephone calls; Starting Time of Call 00,00-06,59
19,01-2359 Rate per Minute 0.12 0.55 0.35 Write a program that asks for the starting time and the number of minutes of rhe call, and displays the charges. The program should ask for the time to be entered as a floating- point number in the form HH.MM. For example, 07:00 hours will be entered as 07.00, and 16:28 hours will be entered as 16.28. Input Validation: The program should not accept times that are greater than 23,59. Also, no number whose las! cwo digits are greater thatt 59 should be accepted. Hzm: Assuming num is a floating-point variable, the following expression will give you its fractional part: num - static_cast<int>(num) 243 244 Chapter 4 Making Decisions 23. In(ernct Servi ce Provider An [merner service provider has three different subscription packages for its customers: Package A: For $9.95 per month 10 hours of access afe provided. Additional h-ou(s are $2.00 per hour. Package B: For $14.95 per month 20 hours of access are provided. Additional hours are $1.00 per hour. Package C: For $19.95 pcr month unli mi ted access is provided. Write a progra m that calculates a customer's monthly bill. It should ask which pack- age the cuStomer has purchased and how many hours were used. It should then dis- play the total amount due. Input Validation: Be sure the user only selects package A, B, or C. Also, the 1Iumber of hOll rs used in a month cannot exceed 744. 24 . Internet Ser vice Provider, Part 2 Modify the in Programming Challenge 23 so that it also displays how much money Package would save if they purchased packages B or C, and how much money B customers would save if they purchased Package C. If there would be no savings, no message should be primed. 25. Internet Service Provider, Part 3 26. Months wi th 30 days have 720 hours, and months with 31 days have 744 hours. Feb- ruary, with 28 days, has 672 hours. Enhance the input validation of the Internet Ser- vice Provider program by asking the user for the month (by name), and validating that the number of hours emered is nO( more than the maximum for the entire month. Here is a table of the months, their days, and number of hours in each. Month Days Hours January 31 744 February 28 672 March 31 744 April 30 no May 31 744 June 30 720 July 31 744 August 31 744 September 30 720 Ocrober 31 744 November 30 720 December 31 7 4'> fife Input (Freezing and Boiling Points Modificacion ) Modify the progra m that you wrote fo r Programming Challenge 20 (Freezing and Boiling Poi nts) so it reads its inpUt from a file instead of the keyboard. Perform the necessary test to determine if an error occurs when (he fi le is opened. If an error occurs, display a message info rming the user.