Page 178 - Introduction to Programming with Java: A Problem Solving Approach
P. 178

                144 Chapter 4 Control Statements
12. Suppose you want to use the user-query technique to terminate a simple while loop. Where should you put
the user query?
§4.9 do Loop
13. What’s wrong with this code fragment?
int x = 3;
do
{
{
}
System.out.println("Happy Birthday# " + age);
age = age + 1;
// end while
x -= 2;
} while (x >= 0)
§4.10 forLoop
14. If you know ahead of time the exact number of iterations through a loop, what type of loop should you use?
15. Implement the following as a for loop:
int age = 0;
while (age < 5)
What output will your equivalent for loop generate?
§4.11 Solving the Problem of Which Loop to Use
16. If you know that a loop should be executed at least one time, what type of loop is most appropriate?
Apago PDF Enhancer
§4.12 Nested Loops
17. Construct a template for a for loop inside a for loop. Use i for the outer for loop’s index variable and
use j for the inner for loop’s index variable.
§4.13 Boolean Variables
18. Assume that the variable OK has been declared to be of type boolean. Replace the following code with an
equivalent for loop: OK = false; while (!OK)
{
<statement(s)>
§4.15 Problem Solving with Boolean Logic (Optional)
19. Given the logical expression: !(!a || !b)
Replace it with an equivalent logical expression that is completely devoid of “not” operations.
Exercises
1. [after §4.3] Whenever you mail a letter, you must decide how much postage to put on the envelope. You like to use this rule of thumb—use one stamp for every five sheets of paper or fraction thereof. For example, if you have 11 sheets of paper, then you use three stamps. To save money, you simply don’t mail the letter if an envelope requires more than three stamps.
Given that the number of sheets is stored in a variable named numSheets, write a code fragment that prompts the user and inputs the number of sheets, calculates the number of stamps required, and prints “Use <number-of-stamps> stamps” or “Don’t mail,” where <number-of-stamps> is an appropriate integer value.
}
 



























































   176   177   178   179   180