Programming in C

(Barry) #1

90 Chapter 6 Making Decisions


To easily test if the value of a flag is FALSE, you can use the logical negation operator,
!. In the expression
if (! isPrime )
the logical negation operator is used to test if the value of isPrimeis FALSE (read this
statement as “if not isPrime”). In general, an expression such as
! expression
negates the logical value of expression. So if expressionis zero, the logical negation
operator produces a 1. And if the result of the evaluation of expressionis nonzero, the
negation operator yields a 0.
The logical negation operator can be used to easily “flip” the value of a flag, such as
in the expression
myMove =! myMove;
As you might expect, this operator has the same precedence as the unary minus opera-
tor, which means that it has higher precedence than all binary arithmetic operators and
all relational operators. So to test if the value of a variable xis not less than the value of a
variable y,such as in
! ( x < y )
the parentheses are required to ensure proper evaluation of the expression. Of course,
you could have equivalently expressed the previous expression as
x >= y
In Chapter 4, “Variables, Data Types, and Arithmetic Expressions,” you learned about
some special values that are defined in the language which you can use when working
with Boolean values.These are the type bool, and the values trueand false.To use
these, you need to include the header file <stdbool.h>inside your program. Program
6.10A is a rewrite of Program 6.10, which takes advantage of this data type and values.

Program 6.10A Revising the Program to Generate a Table of Prime Numbers
// Program to generate a table of prime numbers

#include <stdio.h>
#include <stdbool.h>

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

for ( p = 2; p <= 50; ++p ) {
isPrime = true;
Free download pdf