88 Chapter 6 Making Decisions
printf ("\n");
return 0;
}
Program 6.10 Output
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
Several points are worth noting about the program in Program 6.10.The outermost for
statement sets up a loop to cycle through the integers 2 through 50.The loop variable p
represents the value you are currently testing to see if it is prime.The first statement in
the loop assigns the value 1 to the variable isPrime.The use of this variable will become
apparent shortly.
A second loop is set up to divide pby the integers from 2 through p–1. Inside the
loop, a test is made to see if the remainder of pdivided by dis 0. If it is, you know that p
cannot be prime because an integer other than 1 and itself can evenly divide it.To signal
that pis no longer a candidate as a prime number, the value of the variable isPrimeis
set equal to 0.
When the innermost loop finishes execution, the value of isPrimeis tested. If its
value is not equal to zero, no integer was found that evenly divides p; therefore,pmust
be a prime number, and its value is displayed.
You might have noticed that the variable isPrimetakes on either the value 0 or 1 ,
and no other values.That’s why you declared it to be a _Boolvariable. Its value is 1 as
long as pstill qualifies as a prime number. But as soon as a single even divisor is found,
its value is set to 0 to indicate that pno longer satisfies the criteria for being prime.
Often, variables that are used in such a manner are referred to as flags.A flag typically
assumes only one of two different values. Furthermore, the value of a flag is usually test-
ed at least once in the program to see if it is “on” (TRUE) or “off ” (FALSE), and some
particular action is taken based upon the results of the test.
In C, the notion of a flag being TRUE or FALSE is most naturally translated into the
values 1 and 0 ,respectively. So in the Program 6.10, when you set the value of isPrime
to 1 inside the loop, you are effectively setting it as TRUE to indicate that p“is prime.”
If during the course of execution of the inner forloop an even divisor is found, the
val ue of isPrimeis set to FALSE to indicate that pno longer “is prime.”
It is no coincidence that the value 1 is typically used to represent the TRUE or “on”
state and 0 to represent the FALSE or “off ” state.This representation corresponds to the
notion of a single bit inside a computer.When the bit is “on,” its value is 1 ; when it is
Program 6.10 Continued