20.09.2015 Views

Programming in C

Kochan - ProgramminginC

Kochan - ProgramminginC

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

94 Chapter 6 Mak<strong>in</strong>g Decisions<br />

number. F<strong>in</strong>d out what happens <strong>in</strong> such a case and then modify the program so<br />

that negative numbers are correctly handled. For example, if the number –8645 is<br />

typed <strong>in</strong>, the output of the program should be 5468–.<br />

6. Write a program that takes an <strong>in</strong>teger keyed <strong>in</strong> from the term<strong>in</strong>al and extracts and<br />

displays each digit of the <strong>in</strong>teger <strong>in</strong> English. So, if the user types <strong>in</strong> 932, the program<br />

should display<br />

n<strong>in</strong>e three two<br />

Remember to display “zero” if the user types <strong>in</strong> just a 0. (Note: This exercise is a<br />

hard one!)<br />

7. Program 6.10 has several <strong>in</strong>efficiencies. One <strong>in</strong>efficiency results from check<strong>in</strong>g<br />

even numbers. Because it is obvious that any even number greater than 2 cannot<br />

be prime, the program could simply skip all even numbers as possible primes and<br />

as possible divisors.The <strong>in</strong>ner for loop is also <strong>in</strong>efficient because the value of p is<br />

always divided by all values of d from 2 through p–1.This <strong>in</strong>efficiency could be<br />

avoided by add<strong>in</strong>g a test for the value of isPrime <strong>in</strong> the conditions of the for<br />

loop. In this manner, the for loop could be set up to cont<strong>in</strong>ue as long as no divisor<br />

was found and the value of d was less than p. Modify Program 6.10 to <strong>in</strong>corporate<br />

these two changes.Then run the program to verify its operation. (Note: In<br />

Chapter 7, you discover even more efficient ways of generat<strong>in</strong>g prime numbers.)

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

Saved successfully!

Ooh no, something went wrong!