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.

Boolean Variables<br />

87<br />

switch (operator)<br />

{<br />

...<br />

case '*':<br />

case 'x':<br />

pr<strong>in</strong>tf ("%.2f\n", value1 * value2);<br />

break;<br />

...<br />

}<br />

Boolean Variables<br />

Many new programmers soon f<strong>in</strong>d themselves with the task of hav<strong>in</strong>g to write a program<br />

to generate a table of prime numbers.To refresh your memory, a positive <strong>in</strong>teger p is<br />

a prime number if it is not evenly divisible by any other <strong>in</strong>tegers, other than 1 and itself.<br />

The first prime <strong>in</strong>teger is def<strong>in</strong>ed to be 2.The next prime is 3, because it is not evenly<br />

divisible by any <strong>in</strong>tegers other than 1 and 3, and 4 is not prime because it is evenly divisible<br />

by 2.<br />

There are several approaches that you can take to generate a table of prime numbers.<br />

If you have the task of generat<strong>in</strong>g all prime numbers up to 50, for example, the most<br />

straightforward (and simplest) algorithm to generate such a table is simply to test each<br />

<strong>in</strong>teger p for divisibility by all <strong>in</strong>tegers from 2 through p–1. If any such <strong>in</strong>teger evenly<br />

divided p, then p is not prime; otherwise, it is a prime number. Program 6.10 illustrates<br />

the program to generate a table of prime numbers.<br />

Program 6.10 Generat<strong>in</strong>g a Table of Prime Numbers<br />

// Program to generate a table of prime numbers<br />

#<strong>in</strong>clude <br />

<strong>in</strong>t ma<strong>in</strong> (void)<br />

{<br />

<strong>in</strong>t p, d;<br />

_Bool isPrime;<br />

for ( p = 2; p

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

Saved successfully!

Ooh no, something went wrong!