1. Trang chủ
  2. » Công Nghệ Thông Tin

Absolute C++ (4th Edition) part 9 doc

10 420 2

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 10
Dung lượng 239,64 KB

Nội dung

Loops 81 Display 2.8 A break Statement in a Loop 1 #include <iostream> 2 using namespace std; 3 int main( ) 4 { 5 int number, sum = 0, count = 0; 6 cout << "Enter 4 negative numbers:\n"; 7 while (++count <= 4) 8 { 9 cin >> number; 10 if (number >= 0) 11 { 12 cout << "ERROR: positive number" 13 << " or zero was entered as the\n" 14 << count << "th number! Input ends " 15 << "with the " << count << "th number.\n" 16 << count << "th number was not added in.\n"; 17 break; 18 } 19 sum = sum + number; 20 } 21 cout << sum << " is the sum of the first " 22 << (count - 1) << " numbers.\n"; 23 return 0; 24 } S AMPLE D IALOGUE Enter 4 negative numbers: -1 -2 3 -4 ERROR: positive number or zero was entered as the 3rd number! Input ends with the 3rd number. 3rd number was not added in -3 is the sum of the first 2 numbers. 82 Flow of Control Display 2.9 A continue Statement in a Loop 1 #include <iostream> 2 using namespace std; 3 int main( ) 4 { 5 int number, sum = 0, count = 0; 6 cout << "Enter 4 negative numbers, ONE PER LINE:\n"; 7 while (count < 4) 8 { 9 cin >> number; 10 if (number >= 0) 11 { 12 cout << "ERROR: positive number (or zero)!\n" 13 << "Reenter that number and continue:\n"; 14 continue; 15 } 16 sum = sum + number; 17 count++; 18 } 19 cout << sum << " is the sum of the " 20 << count << " numbers.\n"; 21 return 0; 22 } S AMPLE D IALOGUE Enter 4 negative numbers, ONE PER LINE: 1 ERROR: positive number (or zero)! Reenter that number and continue: -1 -2 3 ERROR: positive number! Reenter that number and continue: -3 -4 -10 is the sum of the 4 numbers. Chapter Summary 83 Self-Test Exercises Chapter Summary Note that you never absolutely need a break or continue statement. The programs in Displays 2.8 and 2.9 can be rewritten so that neither uses either a break or continue statement. The continue statement can be particularly tricky and can make your code hard to read. It may be best to avoid the continue statement completely or at least use it only on rare occasions. ■ NESTED LOOPS It is perfectly legal to nest one loop statement inside another loop statement. When doing so, remember that any break or continue statement applies to the innermost loop (or switch) statement containing the break or continue statement. It is best to avoid nested loops by placing the inner loop inside a function definition and placing a function invocation inside the outer loop. Functions are introduced in Chapter 3. 36. What does a break statement do? Where is it legal to put a break statement? 37. Predict the output of the following nested loops: int n, m; for (n = 1; n <= 10; n++) for (m = 10; m >= 1; m ) cout << n << " times " << m << " = " << n*m << endl; ■ Boolean expressions are evaluated similar to the way arithmetic expressions are evaluated. ■ The C++ branching statements are the if-else statement and the switch state- ment. ■ A switch statement is a multiway branching statement. You can also form multiway branching statements by nesting if-else statements to form a multiway if-else statement. ■ A switch statement is a good way to implement a menu for the user of your pro- gram. ■ The C++ loop statements are the while, do-while, and for statements. ■ A do-while statement always iterates their loop body at least one time. Both a while statement and a for statement might iterate their loop body zero times. ■ A for loop can be used to obtain the equivalent of the instruction “repeat the loop body n times.” 84 Flow of Control ■ A loop can be ended early with a break statement. A single iteration of a loop body may be ended early with a continue statement. It is best to use break statements sparingly. It is best to completely avoid using continue statements, although some programmers do use them on rare occasions. ANSWERS TO SELF-TEST EXERCISES 1. a. true. b. true. Note that expressions a and b mean exactly the same thing. Because the operators == and < have higher precedence than &&, you do not need to include the parentheses. The parentheses do, however, make it easier to read. Most people find the expression in a easier to read than the expression in b, even though they mean the same thing. c. true. d. true. e. false. Since the value of the first subexpression, (count == 1), is false, you know that the entire expression is false without bothering to evaluate the second subexpression. Thus, it does not matter what the values of x and y are. This is short-circuit evaluation. f. true. Since the value of the first subexpression, (count < 10), is true, you know that the entire expression is true without bothering to evaluate the second subexpression. Thus, it does not matter what the values of x and y are. This is short-circuit evaluation. g. false. Notice that the expression in g includes the expression in f as a subexpression. This subexpression is evaluated using short-circuit evaluation as we described for f. The entire expression in g is equivalent to !( (true || (x < y)) && true ) which in turn is equivalent to !( true && true ), and that is equivalent to !(true), which is equivalent to the final value of false. h. This expression produces an error when it is evaluated because the first subexpression, ((limit/count) > 7), involves a division by zero. i. true. Since the value of the first subexpression, (limit < 20), is true, you know that the entire expression is true without bothering to evaluate the second subexpression. Thus, the second subexpression, ((limit/count) > 7) is never evaluated, and so the fact that it involves a division by zero is never noticed by the computer. This is short-circuit evaluation. j. This expression produces an error when it is evaluated because the first subexpression, ((limit/count) > 7), involves a division by zero. Answers to Self-Test Exercises 85 k. false. Since the value of the first subexpression, (limit < 0), is false, you know that the entire expression is false without bothering to evaluate the second subexpression. Thus, the second subexpression, ((limit/count) > 7) is never evaluated, and so the fact that it involves a division by zero is never noticed by the computer. This is short-circuit evaluation. l. If you think this expression is nonsense, you are correct. The expression has no intuitive meaning, but C++ converts the int values to bool and then evaluates the && and ! operations. Thus, C++ will evaluate this mess. Recall that in C++, any nonzero integer converts to true and 0 converts to false, so C++ will evaluate (5 && 7) + (!6) as follows. In the expression (5 && 7), the 5 and 7 convert to true; true && true evaluates to true, which C++ converts to 1. In the expression (!6) the 6 is converted to true, so !(true) evaluates to false, which C++ converts to 0. Thus, the entire expression evaluates to 1 + 0, which is 1. The final value is thus 1. C++ will convert the number 1 to true, but the answer has little intuitive meaning as true; it is perhaps better to just say the answer is 1. There is no need to become proficient at evaluating these nonsense expressions, but doing a few will help you to understand why the compiler does not give you an error message when you make the mistake of mixing numeric and Boolean operators in a single expression. 2. The expression 2 < x < 3 is legal. However, it does not mean (2 < x) && (x < 3) as many would wish. It means (2 < x) < 3. Since (2 < x) is a Boolean expression, its value is either true or false and is thus converted to either 0 or 1, either of which is less than 3. So, 2 < x < 3 is always true. The result is true regardless of the value of x. 3. (x < –1 || (x > 2) 4. (x > 1 && (x < 3) 5. No. In the Boolean expression, (j > 0) is false (j was just assigned -1). The && uses short-circuit evaluation, which does not evaluate the second expression if the truth value can be determined from the first expression. The first expression is false, so the second does not matter. 6. if (score > 100) cout << "High"; else cout << "Low"; You may want to add \n to the end of the above quoted strings, depending on the other details of the program. 86 Flow of Control 7. if (savings >= expenses) { savings = savings - expenses; expenses = 0; cout << "Solvent"; } else { cout << "Bankrupt"; } You may want to add \n to the end of the above quoted strings, depending on the other details of the program. 8. if ( (exam >= 60) && (programsDone >= 10) ) cout << "Passed"; else cout << "Failed"; You may want to add \n to the end of the above quoted strings, depending on the other details of the program. 9. if ( (temperature >= 100) || (pressure >= 200) ) cout << "Warning"; else cout << "OK"; You may want to add \n to the end of the above quoted strings, depending on the other details of the program. 10. All nonzero integers are converted to true; 0 is converted to false. a. 0 is false b. 1 is true c. –1 is true 11. Start Hello from the second if. End Start again End again 12. large 13. small 14. medium 15. Both of the following are correct: if (n < 0) cout << n << " is less than zero.\n"; Answers to Self-Test Exercises 87 else if ((0 <= n) && (n <= 100)) cout << n << " is between 0 and 100 (inclusive).\n"; else if (n >100) cout << n << " is larger than 100.\n"; and if (n < 0) cout << n << " is less than zero.\n"; else if (n <= 100) cout << n << " is between 0 and 100 (inclusive).\n"; else cout << n << " is larger than 100.\n"; 16. 3 2 1 0 17. 2 1 7 5 18. 2 1 0 19. 2 1 20. 1 2 3 4 21. 1 2 3 22. 10 7 4 1 23. There would be no output; the loop is iterated zero times. 24. 10 7 4 1 25. -42 26. With a do-while statement, the loop body is always executed at least once. With a while statement, there can be conditions under which the loop body is not executed at all. 27. 2 4 6 8 28. Hello 10 Hello 8 Hello 6 Hello 4 Hello 2 88 Flow of Control 29. 2.000000 1.500000 1.000000 0.500000 30. a. for (int i = 1; i <= 10; i++) if (i < 5 && i != 2) cout << ‘X’; b. for (int i = 1; i <= 10; i = i + 3) cout << ‘X’; c. cout << ‘X’// necessary to keep output the same. Note // also the change in initialization of n for (long n = 200; n < 1000; n = n + 100) cout << ‘X’; 31. The output is 1024 10. The second number is the base 2 log of the first number. (If the first number is not a power of 2, then only an approximation to the base 2 log is produced.) 32. The output is 1024 1. The semicolon after the first line of the for loop is probably a pit- fall error. 33. This is an infinite loop. Consider the update expression, i = i * 2. It cannot change i because its initial value is 0, so it leaves i at its initial value, 0. It gives no output because of the semicolon after the first line of the for loop. 34. a. A for loop b. and c. Both require a while loop because the input list might be empty. d. A do-while loop can be used because at least one test will be performed. 35. This is an infinite loop. The first few lines of output are as follows: 10 13 16 19 21 36. A break statement is used to exit a loop (a while, do-while, or for statement) or to ter- minate a switch statement. A break statement is not legal anywhere else in a C++ pro- gram. Note that if the loops are nested, a break statement only terminates one level of the loop. 37. The output is too long to reproduce here. The pattern is as follows: 1 times 10 = 10 1 times 9 = 9 . . . Programming Projects 89 1 times 1 = 1 2 times 10 = 20 2 times 9 = 18 . . . 2 times 1 = 2 3 times 10 = 30 . . . PROGRAMMING PROJECTS 1. It is difficult to make a budget that spans several years, because prices are not stable. If your company needs 200 pencils per year, you cannot simply use this year’s price as the cost of pencils two years from now. Because of inflation the cost is likely to be higher than it is today. Write a program to gauge the expected cost of an item in a specified number of years. The program asks for the cost of the item, the number of years from now that the item will be purchased, and the rate of inflation. The program then outputs the estimated cost of the item after the specified period. Have the user enter the inflation rate as a per- centage, such as 5.6 (percent). Your program should then convert the percentage to a frac- tion, such as 0.056, and should use a loop to estimate the price adjusted for inflation. (Hint: Use a loop.) 2. You have just purchased a stereo system that cost $1000 on the following credit plan: no down payment, an interest rate of 18% per year (and hence 1.5% per month), and monthly payments of $50. The monthly payment of $50 is used to pay the interest, and whatever is left is used to pay part of the remaining debt. Hence, the first month you pay 1.5% of $1000 in interest. That is $15 in interest. The remaining $35 is deducted from your debt, which leaves you with a debt of $965.00. The next month you pay interest of 1.5% of $965.00, which is $14.48. Hence, you can deduct $35.52 (which is $50–$14.48) from the amount you owe. Write a program that will tell you how many months it will take you to pay off the loan, as well as the total amount of interest paid over the life of the loan. Use a loop to calculate the amount of interest and the size of the debt after each month. (Your final program need not output the monthly amount of interest paid and remaining debt, but you may want to write a preliminary version of the program that does output these values.) Use a variable to count the number of loop iterations and hence the number of months until the debt is zero. You may want to use other variables as well. The last payment may be less than $50 if the debt is small, but do not forget the interest. If you owe $50, then your monthly pay- ment of $50 will not pay off your debt, although it will come close. One month’s interest on $50 is only 75 cents. For additional online Programming Projects, click the CodeMate icons below. 2.3 1.7 2.5 2.6 2.7 3 Function Basics 3.1 PREDEFINED FUNCTIONS 92 Predefined Functions That Return a Value 92 Predefined void Functions 97 A Random Number Generator 99 3.2 PROGRAMMER-DEFINED FUNCTIONS 103 Defining Functions That Return a Value 103 Alternate Form for Function Declarations 106 Pitfall: Arguments in the Wrong Order 107 Pitfall: Use of the Terms Parameter and Argument 107 Functions Calling Functions 107 Example: A Rounding Function 107 Functions That Return a Boolean Value 110 Defining void Functions 111 return Statements in void Functions 112 Preconditions and Postconditions 113 main Is a Function 115 Recursive Functions 116 3.3 SCOPE RULES 117 Local Variables 117 Procedural Abstraction 120 Global Constants and Global Variables 121 Blocks 124 Nested Scopes 124 Tip: Use Function Calls in Branching and Loop Statements 125 Variables Declared in a for Loop 125 CHAPTER SUMMARY 126 ANSWERS TO SELF-TEST EXERCISES 127 PROGRAMMING PROJECTS 130 . Function Basics 3.1 PREDEFINED FUNCTIONS 92 Predefined Functions That Return a Value 92 Predefined void Functions 97 A Random Number Generator 99 3.2 PROGRAMMER-DEFINED FUNCTIONS 103 Defining. reproduce here. The pattern is as follows: 1 times 10 = 10 1 times 9 = 9 . . . Programming Projects 89 1 times 1 = 1 2 times 10 = 20 2 times 9 = 18 . . . 2 times 1 = 2 3 times 10 = 30 . . . PROGRAMMING. no intuitive meaning, but C++ converts the int values to bool and then evaluates the && and ! operations. Thus, C++ will evaluate this mess. Recall that in C++, any nonzero integer converts

Ngày đăng: 04/07/2014, 05:21

TỪ KHÓA LIÊN QUAN