Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 40 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
40
Dung lượng
400,52 KB
Nội dung
80 Flow of Control 34. For each of the following situations, tell which type of loop (while, do-while, or for) would work best. a. Summing a series, such as 1/2 + 1/3 + 1/4 + 1/5 + . . . + 1/10. b. Reading in the list of exam scores for one student. c. Reading in the number of days of sick leave taken by employees in a department. d. Testing a function to see how it performs for different values of its arguments. 35. What is the output produced by the following? ( x is of type int.) int x = 10; while (x > 0) { cout << x << endl; x = x + 3; } ■ THE break AND continue STATEMENTS In previous subsections, we have described the basic flow of control for the while, do- while , and for loops. This is how the loops should normally be used and is the way they are usually used. However, you can alter the flow of control in two ways, which in rare cases can be a useful and safe technique. The two ways of altering the flow of con- trol are to insert a break or continue statement. The break statement ends the loop. The continue statement ends the current iteration of the loop body. The break state- ment can be used with any of the C++ loop statements. We described the break statement when we discussed the switch statement. The break statement consists of the keyword break followed by a semicolon. When exe- cuted, the break statement ends the nearest enclosing switch or loop statement. Dis- play 2.8 contains an example of a break statement that ends a loop when inappropriate input is entered. The continue statement consists of the keyword continue followed by a semicolon. When executed, the continue statement ends the current loop body iteration of the nearest enclosing loop statement. Display 2.9 contains an example of a loop that con- tains a continue statement. One point that you should note when using the continue statement in a for loop is that the continue statement transfers control to the update expression. So, any loop control variable will be updated immediately after the continue statement is executed. Note that a break statement completely ends the loop. In contrast, a continue statement merely ends one loop iteration; the next iteration (if any) continues the loop. You will find it instructive to compare the details of the programs in Displays 2.8 and 2.9. Pay particular attention to the change in the controlling Boolean expression. continue statement 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 [...]... a function in C++ This chapter presents the basic details about C++ functions Before telling you how to write your own functions, we will first tell you how to use some predefined C++ functions 3.1 Predefined Functions Do not reinvent the wheel Common saying void function C++ comes with libraries of predefined functions that you can use in your programs There are two kinds of functions in C++: functions... wrong type, then, in many cases, some automatic type conversion will be done for you by C++ However, the results may not be what you intended Self-Test Exercises 1 Determine the value of each of the following arithmetic expressions sqrt(16.0) sqrt(16) pow(2.0, 3.0) pow(2, 3) pow(2.0, 3) pow(1.1, 2) abs (3) abs( -3) abs(0) fabs(-3.0) fabs(-3.5) fabs(3.5) ceil(5.1) ceil(5.8) floor(5.1) floor(5.8) pow(3.0,... functions must contain the following directive: #include Also notice that there are three absolute value functions If you want to produce the absolute value of a number of type int, use abs; if you want to produce the absolute value of a number of type long, use labs; and if you want to produce the absolute value of a number of type double, use fabs To complicate things even more, abs and labs... sqrt Square root double double sqrt(4.0) 2.0 cmath pow Powers double double pow(2.0,3.0) 8.0 cmath abs Absolute value for int int abs(-7) abs(7) 7 7 cstdlib long long labs(-70000) labs(70000) 70000 70000 cstdlib double double fabs(-7.5) fabs(7.5) 7.5 7.5 cmath int labs Absolute value for long fabs Absolute value for double ceil Ceiling (round up) double double ceil(3.2) ceil(3.9) 4.0 4.0 cmath floor... you You should still scan this chapter to see the C++ syntax and terminology for the basics of functions Chapter 4 contains the material on functions that might be different in C++ than in other languages A program can be thought of as consisting of subparts such as obtaining the input data, calculating the output data, and displaying the output data C++, like most programming languages, has facilities... and code each of these subparts separately In C++ these subparts are called functions Most programming languages have functions or something similar to functions, although they are not always called by that name in other languages The terms procedure, subprogram, and method, which you may have heard before, mean essentially the same thing as function In C++ a function may return a value (produce a value)... header file cmath fabs is an abbreviation for floating-point absolute value Recall that numbers with a fraction after the decimal point, such as numbers of type double, are often called floating-point numbers Another example of a predefined function is pow, which is in the library with header file cmath The function pow can be used to do exponentiation in C++ For example, if you want to set a variable result... pow(3.0, 2)/2 7/abs(-2) (7 + sqrt(4.0))/3.0 sqrt(pow(3, 2)) 2 Convert each of the following mathematical expressions to a C++ arithmetic expression a x + y time + tide d -nobody b x y + 7 c area + fudge b2 –b + – 4ac e 2a f x – y 3 Write a complete C++ program to compute and output the square roots of the whole numbers from 1 to 10 4 What is the function of the int argument... terminated with a semicolon If there is more than one argument, the arguments are separated by commas For a void function, a function invocation (function call) is a statement that can be used like any other C++ statement SYNTAX Function_Name(Argument_List); where the Argument_List is a comma-separated list of arguments: Argument_1, Argument_2, , Argument_Last EXAMPLE exit(1); function pow, you can safely... immediately Display 3.3 contains a toy program that demonstrates the exit function Note that the function exit has one argument, which is of type int The argument is given to the operating system As far as your C++ program is concerned, you can use Display 3.3 A Function Call for a Predefined void Function 1 2 3 #include #include using namespace std; 4 5 6 7 int main( ) { cout . the arrival of cars at a toll booth. sqrt(16.0) sqrt(16) pow(2.0, 3.0) pow(2, 3) pow(2.0, 3) pow(1.1, 2) abs (3) abs( -3) abs(0) fabs(-3.0) fabs(-3.5) fabs(3.5) ceil(5.1) ceil(5.8) floor(5.1) floor(5.8). notice that there are three absolute value functions. If you want to produce the absolute value of a number of type int , use abs ; if you want to produce the absolute value of a number. pow(2.0,3.0) 8.0 cmath abs Absolute value for int int int abs(-7) abs(7) 7 7 cstdlib labs Absolute value for long long long labs(-70000) labs(70000) 70000 70000 cstdlib fabs Absolute value for double double