Programming in C

(Barry) #1
Boolean Variables 87

switch (operator)
{


case '*':
case 'x':
printf ("%.2f\n", value1 * value2);
break;

}


Boolean Variables


Many new programmers soon find themselves with the task of having to write a pro-
gram to generate a table of prime numbers.To refresh your memory, a positive integer pis
a prime number if it is not evenly divisible by any other integers, other than 1 and itself.
The first prime integer is defined to be 2.The next prime is 3, because it is not evenly
divisible by any integers other than 1 and 3, and 4 is notprime because it isevenly divis-
ible by 2.
There are several approaches that you can take to generate a table of prime numbers.
If you have the task of generating all prime numbers up to 50, for example, the most
straightforward (and simplest) algorithm to generate such a table is simply to test each
integer pfor divisibility by all integers from 2 through pā€“1. If any such integer evenly
divided p, then pis not prime; otherwise, it is a prime number. Program 6.10 illustrates
the program to generate a table of prime numbers.


Program 6.10 Generating a Table of Prime Numbers


// Program to generate a table of prime numbers


#include <stdio.h>


int main (void)
{
int p, d;
_Bool isPrime;


for ( p = 2; p <= 50; ++p ) {
isPrime = 1;

for ( d = 2; d < p; ++d )
if ( p % d == 0 )
isPrime = 0;

if ( isPrime != 0 )
printf ("%i ", p);
}
Free download pdf