C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1
if (!(baseball + basketball > football))
{
printf("\nThere are fewer baseball and basketball players\n");
printf("combined than football players.");
}
else
{
printf("\nThere are more baseball and basketball players\n");
printf("combined than football players.");
}
return 0;
}

Experiment with this program—change the conditions, variables, and operators to get different
printing combinations. As mentioned before, the most confusing logical operator is the last one in the
program, the not (!) operator. Most of the time, you can write a statement that avoids the use of it.


Avoiding the Negative


Suppose you wanted to write an inventory program that tests whether the number of a certain item has
fallen to zero. The first part of the if might look like this:


if (count == 0) {

Because the if is true only if count has a value of 0 , you can rewrite the statement like this:


Click here to view code image


if (!count) { /* Executes if's body only if count is 0 */

Again, the! adds a little confusion to code. Even though you might save some typing effort with a
fancy !, clearer code is better than trickier code, and if (count == 0) { is probably better to
use, despite the microsecond your program might save by using !.


Using the && operator, the following program prints one message if the user’s last name begins with
the letters P through S, and it prints another message if the name begins with something else.


Click here to view code image


// Example program #2 from Chapter 12 of Absolute Beginner's Guide
// to C, 3rd Edition
// File Chapter12ex2.c
/* This program asks for a last name, and if the user has a last
name that starts with a letter between P and Q, they will be sent to
a special room for their tickets. */
#include <stdio.h>

main()
{
// set up an array for the last name and then get it from the user
char name[25];
printf("What is your last name? ");
Free download pdf