19.09.2015 Views

Prentice.Hall.Introduction.to.Java.Programming,.Brief.Version.9th.(2014).[sharethefiles.com]

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

174 Chapter 4 Loops<br />

*4.42 (Financial application: find the sales amount) Rewrite Exercise 4.39 as follows:<br />

■ Use a for loop instead of a do-while loop.<br />

■ Let the user enter COMMISSION_SOUGHT instead of fixing it as a constant.<br />

*4.43 (Simulation: clock countdown) Write a program that prompts the user <strong>to</strong> enter the<br />

number of seconds, displays a message at every second, and terminates when the<br />

time expires. Here is a sample run:<br />

Enter the number of seconds:<br />

2 seconds remaining<br />

1 second remaining<br />

S<strong>to</strong>pped<br />

3<br />

**4.44 (Monte Carlo simulation) A square is divided in<strong>to</strong> four smaller regions as shown<br />

below in (a). If you throw a dart in<strong>to</strong> the square 1,000,000 times, what is the probability<br />

for a dart <strong>to</strong> fall in<strong>to</strong> an odd-numbered region? Write a program <strong>to</strong> simulate<br />

the process and display the result.<br />

(Hint: Place the center of the square in the center of a coordinate system, as shown<br />

in (b). Randomly generate a point in the square and count the number of times for<br />

a point <strong>to</strong> fall in<strong>to</strong> an odd-numbered region.)<br />

1<br />

3<br />

4<br />

2<br />

1<br />

3<br />

4<br />

2<br />

(a)<br />

(b)<br />

*4.45 (Math: <strong>com</strong>binations) Write a program that displays all possible <strong>com</strong>binations for<br />

picking two numbers from integers 1 <strong>to</strong> 7. Also display the <strong>to</strong>tal number of all<br />

<strong>com</strong>binations.<br />

1 2<br />

1 3<br />

...<br />

...<br />

The <strong>to</strong>tal number of all <strong>com</strong>binations is 21<br />

*4.46 (Computer architecture: bit-level operations) A short value is s<strong>to</strong>red in 16 bits.<br />

Write a program that prompts the user <strong>to</strong> enter a short integer and displays the 16<br />

bits for the integer. Here are sample runs:<br />

Enter an integer: 5<br />

The bits are 0000000000000101

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!