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

(Romina) #1
printf("(Please capitalize the first letter!)\n");
scanf(" %s", name);
//For a string array, you don't need the &
if ((name[0] >= 'P') && (name[0] <= 'S'))
{
printf("You must go to room 2432 ");
printf("for your tickets.\n");
}
else
{
printf("You can get your tickets here.\n");
}
return 0;
}

One point about this program is worth noting. Chapter 8, “Interacting with Users,” suggested that you
use your printf() statement to clarify what data you need from the user and in what format.
Reminding users to type their last name using a capital letter helps avoid possible problems. If your
user’s last name is Peyton, but she types it as peyton with a lowercase p, the program would not
send the user to Room 2432 because the logical operator checks only for capitals. Now, if you
wanted to check for either, you could use the following, more complicated, logical statement:


Click here to view code image


if (((name[0] >= 'P') && (name[0] <= 'S')) || (name[0] >= 'p') &&
(name[0] >= 's')))

It’s a little harder to read and follow, but such is the price of data vigilance!


Note

How would the program be different if the && were changed to a ||? Would the first
or the second message appear? The answer is the first one. Everybody would be sent
to Room 2432. Any letter from A to Z is either more than P or less than S. The test in
the preceding program has to be && because Room 2432 is available only to people
whose names are between P and S.

As mentioned in the last chapter, if statements can be helpful when ensuring that the user has entered
the proper information your program is looking for. The following section of code asks the user for a
Y or N answer. The code includes an || to ensure that the user enters a correct value.


Click here to view code image


printf("Is your printer on (Y/N) ?\n");
scanf(" %c", &ans); //need an & before the name of your char variable
if ((ans == 'Y') || (ans == 'N'))
{
// Gets here if user typed a correct answer.
if (ans == 'N')
Free download pdf