The < symbol between them means “less than.” The test reads “If the value of the variable number is less than 5.” If this is true, the cluster of statements following the if keyword is e
Trang 1The if keyword allows you to put these types of decisions into your programs The decisions are based on a comparison For example:
If the contents of the variable calories are very high, it must taste very
good
If it ain’t broke, don’t fix it
If Doug doesn’t ask me out to the prom, I’ll have to go with Charley All these examples show important decisions, similar to those you can make
in your C programs by using the if keyword However, in the C programming language, the if keyword’s comparisons are kind of, sort of — dare I say it? — mathematical in nature Here are more accurate examples:
If the value of variable A is equal to the value of variable
If the contents of variable ch
If the value of variable zed
These examples are really simple, scales-of-justice evaluations of variables and values The if keyword makes the comparison, and if the comparison is true, your program does a particular set of tasks
if is a keyword in the C programming language It allows your programs
to make decisions
if decides what to do based on a comparison of (usually) two items
The comparison that if makes is mathematical in nature: Are two items equal to, greater than, less than — and so on — to each other? If they are, a certain part of your program runs If not, that part of the program doesn’t run
The if keyword creates what is known as a selection statement in the C
language I wrote this topic down in my notes, probably because it’s in
some other C reference I have read at some time or another Selection
statement Impress your friends with that term if you can remember it Just
throw your nose in the air if they ask what it means (That’s what I do.)
The following program is GENIE1.C, one of many silly computer number programs you write when you find out how to program Computer scientists used to play these games for hours in the early days of the computer They would probably drop dead if we could beam a Sony PlayStation back through time
Trang 2guess-the-What GENIE1.C does is to ask for a number, from 0 through 9 You type that number at the keyboard Then, using the magic of the if statement, the com
puter tells you whether the number you entered is less than 5 This program was a major thigh-slapper when it was first written in the early 1950s
Enter the following source code into your text editor The only new stuff comes with the if statement cluster, near the end of the program Better double-double-check your typing
#include <stdio.h>
#include <stdlib.h>
int main() {
char num[2];
int number;
printf(“I am your computer genie!\n”);
printf(“Enter a number from 0 to 9:”);
gets(num);
number=atoi(num);
if(number<5) {
printf(“That number is less than 5!\n”);
} printf(“The genie knows all, sees all!\n”);
return(0);
}
I am your computer genie!
Enter a number from 0 to 9:
Type a number, somewhere in the range of 0 through 9 For example, you can type 3 Press Enter and you see:
That number is less than 5!
The genie knows all, sees all!
Trang 3The #include <stdlib.h> part is necessary because the program uses the atoi() function
The if command is followed by parentheses, which contain the comparison that the if keyword tests
The comparison that if makes tests the value of the variable number
with 5 The < symbol between them means “less than.” The test reads “If the value of the variable number is less than 5.” If this is true, the cluster
of statements following the if keyword is executed If the test proves false, the cluster of statements is skipped
Remember the < — less than — from school? Good!
Notice that the if test isn’t followed by a semicolon! Instead, it’s followed by a statement enclosed in curly braces The statements (there can be more than one) “belong” to the if command and are executed
only if the condition is true
If you see only the line The genie knows all, sees all!, you probably typed a number greater than 4 (which includes 5 and higher) The reason is that the if statement tests only for values less than 5 If the
value is less than 5, That number is less than 5! is displayed The next section elaborates on how it all works
No, the computer genie doesn’t know all and see all if you type a number
Trang 4Figure 12-1:
How
printf("whatever");
if(chins>3) {
printf("Where is your neck?");
} printf("something else");
Program execution
?
False True
if is followed by a set of parentheses in which a comparison is made The
comparison is mathematical in nature, using the symbols shown in Table 12-1
What’s being compared is usually the value of a variable against a constant value, or two variables against each other (See Table 12-1 for examples.)
If the result of the comparison is true, the statement (or group of statements)
between the curly braces is executed If the result is false, the stuff in the curly braces is conveniently skipped over — ignored like a geeky young lad
at his first high school dance and with a zit the size of Houston on his chin
Yes, the curly braces that follow if can contain more than one statement
And, each of the statements ends with a semicolon All are enclosed in the
curly braces It’s technically referred to as a code block It shows you which
statements “belong” to if The whole darn thing is part of the if statement
Table 12-1 Operators Used in if Comparisons
Comparison Meaning or Pronunciation “True” Examples
Trang 5Table 12-1 (continued) Comparison Meaning or Pronunciation “True” Examples
printf(“That number is less than 5!\n”);
}
The first line is the if keyword and its comparison in parentheses What’s being compared is the value of the numeric variable number and the constant value 5 The comparison is “less than.” Is number less than 5? If so, the statement in curly braces is executed If not, the whole deal is skipped over Consider these modifications:
if(number==5) {
printf(“That number is more than 4!\n”);
}
Trang 6This time, the test is greater than or equal to: Is the number that is entered 5
or more than 5? If the number is greater than or equal to 5, it must be more than 4, and the printf() statement goes on to display that important info on the screen
The following modification to the GENIE1.C program doesn’t change the if
comparison, as in the previous examples Instead, it shows you that more than one statement can belong to if:
if(number<5) {
printf(“That number is less than 5!\n”);
printf(“By goodness, aren’t I smart?\n”);
}
Everything between the curly braces is executed when the comparison is true
Advanced C programs may have lots of stuff in there; as long as it’s between the curly braces, it’s executed only if the comparison is true (That’s why it’s indented — so that you know that it all belongs to the if statement.)
The comparison that if makes is usually between a variable and a value
It can be a numeric or single-character variable
if cannot compare strings For information on comparing strings, refer
to my book C All-in-One Desk Reference For Dummies (Wiley)
Less than and greater than and their ilk should be familiar to you from basic math If not, you should know that you read the symbols from left
to right: The > symbol is greater than because the big side comes first;
the < is less than because the lesser side comes first
The symbols for less than or equal to and greater than or equal to always appear that way: <= and >= Switching them the other way generates an error
The symbol for “not” in C is the exclamation point So, != means “not equal.” What is !TRUE (not-true) is FALSE “If you think that it’s butter, but it’s !.” No, I do ! want to eat those soggy zucchini chips
When you’re making a comparison to see whether two things are equal,
you use two equal signs I think of it this way: When you build an if
statement to see whether two things are equal, you think in your head
“is equal” rather than “equals.” For example:
if(x==5)
Read this statement as “If the value of the x variable is equal to 5, then .” If you think “equals,” you have a tendency to use only oneequal sign — which is very wrong
Trang 7If you use one equal sign rather than two, you don’t get an error; however, the program is wrong The nearby Technical Stuff sidebar attempts
to explain why
If you have programmed in other computer languages, keep in mind that the C language has no 2ewd or fi word The final curly brace signals to the compiler that the if statement has ended
Also, no then word is used with if, as in the if-then thing they have in the BASIC or Pascal programming language
A question of formatting the if
The if statement is your first “complex” C language statement The C language has many more, but if is the first and possibly the most popular, though I doubt that a popularity contest for programming language words has ever been held (and, then again, if would be great as Miss Congeniality but definitely come up a little thin in the swimsuit competition)
Though you probably have seen the if statement used only with curly braces, it can also be displayed as a traditional C language statement For example, consider the following — one of the modifications from the GENIE1 program:
if(number==5) {
printf(“That number is 5!\n”);
}
In C, it’s perfectly legitimate to write this as a more traditional type of statement To wit:
if(number==5) printf(“That number is 5!\n”);
This line looks more like a C language statement It ends in a semicolon Everything still works the same; if the value of the number variable is equal
to 5, the printf() statement is executed If number doesn’t equal 5, the rest
of the statement is skipped
Although all this is legal and you aren’t shunned in the C programming community for using it, I recommend using curly braces with your if statements until you feel comfortable reading the C language
Trang 8Clutter not thy head with this comparison nonsense
The comparison in the if
have to use any symbols at all! Strange but true
What the C compiler does is to figure out what you have put between the parentheses Then it For a comparison using <, >, ==, or any of the whether the comparison is true or false
any valid C statement — between the paren
theses and the compiler determines whether it works out to true or false For example:
if(input=1)
This if
the value of the input variable is equal to 1
No, you need two equal signs for that Instead,
what happens between these parentheses is that the numeric variable input is given the value 1
input=1;
The C compiler obeys this instruction, stuffing 1 into the input variable Then, it sits back and strokes its beard and thinks, “Does that work out to be true or false?” Not knowing any true It tells the if keyword, and the cluster of statements that belong to the ifstatement are then executed
statement doesn’t
weighs whether it’s true or false
horde in Table 12-1, the compiler figures out However, you can stick just about anything —
statement doesn’t figure out whether
It’s the same as
better, it figures that the statement must be
The final solution to the income-tax problem
I have devised what I think is the fairest and most obviously well-intentioned way to decide who must pay the most in income taxes You should pay more taxes if you’re taller and more taxes if it’s warmer outside Yessir, it would be hard to dodge this one
This problem is ideal for the if keyword to solve You pay taxes based on either your height or the temperature outside, multiplied by your favorite number and then 10 Whichever number is higher is the amount of tax you pay To figure out which number is higher, the program TAXES.C uses the if
keyword with the greater-than symbol It’s done twice — once for the height value and again for the temperature outside:
Trang 9#include <stdio.h>
#include <stdlib.h>
int main() {
tax1 = atoi(height) * atoi(favnum);
tax2 = atoi(temp) * atoi(favnum);
if(tax1>tax2) {
printf(“You owe $%d in taxes.\n”,tax1*10);
} if(tax2>=tax1) {
printf(“You owe $%d in taxes.\n”,tax2*10);
} return(0);
}
This program is one of the longer ones in this book Be extra careful when you’re typing it It has nothing new in it, but it covers almost all the information I present in the first several chapters Double-check each line as you type
it into your editor
Save the file to disk as TAXES.C
Compile TAXES.C Fix any errors you see
Run the program:
Enter your height in inches:
Type your height in inches Five feet is 60 inches; six feet is 72 inches The average person is 5'7" tall or so — 67 inches Press Enter
What temperature is it outside?
Right now, in the bosom of winter in the Pacific Northwest, it’s 18 degrees That’s Fahrenheit, by the way Don’t you dare enter the smaller Celsius number
If you do, the IRS will hunt you down like a delinquent country music star and make you pay, pay, pay
Trang 10Enter your favorite number:
Type your favorite number Mine is 11 Press Enter
If I type 72 (my height), 18, and 11, for example, I see the following result, due April 15:
You owe $7920 in taxes
Sheesh! And I thought the old system was bad I guess I need a smaller favorite number
The second if comparison is “greater than or equal to.” This catches the case when your height is equal to the temperature If both values are equal, the values of both the tax1 and tax2 variables are equal The first if comparison, “tax1 is greater than tax2,” fails because both are equal The second comparison, “tax1 is greater than or equal to tax2,”
passes when tax1 is greater than tax2 or when both values are equal
If you enter zero as your favorite number, the program doesn’t say that you owe any tax Unfortunately, the IRS does not allow you to have zero —
or any negative numbers — as your favorite number Sad, but true
Hold on to that tax problem!
No, not the one the government created Instead, hold on to the TAXES.C source code introduced in the preceding section If it’s already in your text editor, great Otherwise, open it in your editor for editing
The last part of the TAXES.C program consists of two if statements The second if statement, which should be near Line 23 in your editor, really isn’t necessary Rather than use if in that manner, you can take advantage of another word in the C language, else
Change Line 23 in the TAXES.C program It looks like this now:
Trang 11Save the file back to disk
Compile TAXES.C Run the final result The output is the same because the program hasn’t changed (and assuming that it hasn’t gotten any warmer and you haven’t grown any taller in the past few moments) What you have done
is to create an if-else structure, which is another way to handle the
decision-making process in your C programs
The else keyword is a second, optional part of an if cluster of statements It groups together statements that are to be executed when the condition that if tests for isn’t true
Or else what?
Alas, if you enter the same values as in the old program, you still owe the same bundle to Uncle Sam
Covering all the possibilities with
The if-else keyword combination allows you to write a program that can make either-or decisions By itself, the if keyword can handle minor decisions and execute special instructions if the conditions are just so But when
if is coupled with else, your program takes one of two directions, depending on the comparison if makes Figure 12-2 illustrates how this can happen
printf("whatever");
if(chins>3) {
printf("Where is your neck?");
} else { printf("My, but what a slender neck."); }
printf("something else");
Program execution
Trang 12If the comparison is true, the statements belonging to the if statement are executed But, if the comparison is false, the statements belonging to the
else are executed The program goes one way or the other, as illustrated
in Figure 12-2 Then, after going its own way, the statement following the
else’s final curly brace is executed, like this: “You guys go around the left side of the barn, we’ll go around the right, and we’ll meet you on the other side.”
The if format with
The else keyword is used in an if statement The keyword holds its own group of statements to be executed (okay, “obeyed”) when the if compari
son isn’t true Here’s the format:
if(comparison)
{
statement(s);
} else {
statement(s);
}
The if keyword tests the comparison in parentheses If it’s a true comparison — no foolin’ — the statements that appear in curly braces right after the if statement are executed But, if the comparison is false, those statements following the else keyword and enclosed in curly braces are executed One way or another, one group of statements is executed and the other isn’t
The else keyword, like all words in the C language, is in lowercase It isn’t followed by a semicolon Instead, a set of curly braces follows the else The curly braces enclose one or more statements to be run when the comparison that if makes isn’t true Notice that those statements each must end in a semicolon, obeying the laws of C first etched in stone by the ancient Palo Altoites
The statements belonging to the else keyword are executed when the condi
tion that the if keyword evaluates is false Table 12-2 illustrates how it works, showing you the opposite conditions for the comparisons that an if keyword would make
Trang 13Table 12-2 if Comparisons and Their Opposites
if Comparison else Statement Executed By This Condition
< >= (Greater than or equal to)
> <= (Less than or equal to)
<= > (Greater than)
I don’t know about you, but I think that all those symbols in Table 12-2 would certainly make an interesting rug pattern
The else keyword is used only with if
Both if and else can have more than one statement enclosed in their curly braces if’s statements are executed when the comparison is true;
else’s statements are executed when the comparison is false
To execute means to run C programs execute, or run, statements from
the top of the source code (the first line) to the bottom Each line is executed one after the other unless statements like if and else are encountered In that case, the program executes different statements, depending on the comparison that if makes
When your program doesn’t require an either-or decision, you don’t have to use else For example, the TAXES program has an either-or decision But, suppose that you’re writing a program that displays an error message when something doesn’t work In that case, you don’t need
else; if an error doesn’t occur, the program should continue as normal
If you’re the speaker of another programming tongue, notice that the C language has no end-else word in it This isn’t smelly old Pascal, for goodness’ sake The final curly brace signals the end of the else statement, just as it does with if
The strange case of else-if
and even more decisions
The C language is rich with decision making The if keyword helps if you need to test for only one condition True or false, if handles it And, if it’s true, a group of statements is executed Otherwise, it’s skipped over (After the if’s group of statements is executed, the program continues as before.)
Trang 14Silly formatting trivia
The if-else structure need not be laden with curly braces Just as you can abbre
heavy-viate an if statement to one line, you can also abbreviate else
program that illustrates examples this crudely:
if(tax1>tax2) {
printf(“You owe $%i in taxes.\n”,tax1*10);
} else { printf(“You owe $%i in taxes.\n”,tax2*10);
else printf(“You owe $%i in taxes.\n”,tax2*10);
This format keeps the indenting intact, which is one way to see what belongs to what (and also
to easily identify the if-else structure) The following format is also possible, though it makes the program hard to read:
if(tax1>tax2) printf(“You owe
$%i in taxes.\n”,tax1*10);
else printf(“You owe $%i in taxes.\n”,tax2*10);
Everything is scrunched up on two lines; the if
statement has its own line, and the elsehas its own line Both lines end with a semicolon, which is how this works as two statements in
braces — whenever only one statement appears with an if or else keyword If multi
ple statements must be executed, you’re why I recommend them all the time: No sense
if(tax1>tax2) printf(“You owe $%i in taxes.\n”,tax1*10);
else { printf(“You owe $%i in taxes.\n”,tax2*10);
printf(“It pays to live where it’s cold!\n”);
}
Because two printfstatements belong to the preceding else, the curly braces are required
I don’t recommend it, which
is why I’m terribly brief and don’t ever show a
of the TAXES.C program: the
the C language But, look-it It’s gross! Please don’t write your programs this way
You can do this trick — eliminating the curly
required by law to use the curly braces That’s risking prison over brevity To wit:
Either-or conditions are the daily bread of the if-else duo Either way, one set of statements is executed and not the other, depending on the compari
son made by if What about “one, two, or the third” types of decisions? For them, you need the miraculous and overly versatile else-if combination It really drives you batty, but it’s handy
Trang 15The following program is a modification of the GENIE1.C source code, as shown earlier in this chapter This time, the else-if combination is used to allow the computer genie to accurately report whether the number is less than 5, equal to 5, or greater than 5:
#include <stdio.h>
#include <stdlib.h>
int main() {
char num[2];
int number;
printf(“I am your computer genie!\n”);
printf(“Enter a number from 0 to 9:”);
gets(num);
number=atoi(num);
if(number<5) {
printf(“That number is less than 5!\n”);
} else if(number==5) {
printf(“You typed in 5!\n”);
} else { printf(“That number is more than 5!\n”);
} printf(“The genie knows all, sees all!\n”);
return(0);
}
Start working on this source code by loading the GENIE1.C source code I show you how to create earlier in this chapter Make modifications so that the latter part of the program looks like the new, GENIE2.C source code that was just listed
Watch your indenting Pay attention to everything; two equal signs are in the
else-if comparison Pay attention to where semicolons go and where they don’t go
After inserting the new lines, save the file to disk as GENIE2.C
Compile GENIE2.C If the error monster rears its ugly head, reedit the source code and then recompile
Trang 16Run the final result and see how much more clairvoyant the computer genie
has become Type 3 and see That number is less than 5! Type 9 and
see That number is more than 5! Type 5 and the genie knows: You typed in 5!
The else-if comparison resembles combined else and if statements
The second if comes right after else and a space Then, it has its own comparison statement, which is judged either true or false
In GENIE2.C, the else-if comparison is number==5, testing to see whether the value of the number variable is 5 Two equal signs are used for this comparison
You can do else-if, else-if, else-if all day long, if you want How
ever, the C language has a better solution in the select-case structure
I cover this topic in this book’s companion volume, C All-in-One Desk
Reference For Dummies (Wiley)
Bonus program! The really, really smart genie
A solution always exists If you wanted to, you could write a program that would if-compare any value, from zero to infinity and back again, and the
“computer genie” would accurately guess it But, why bother with if at all?
Okay, the if keyword is the subject of this section, along with if-else and
else-if and so on But, the following source code for GENIE3.C doesn’t use
if at all It cheats so that the genie always guesses correctly:
#include <stdio.h>
int main() {
char num;
printf(“I am your computer genie!\n”);
printf(“Enter a number from 0 to 9:”);
num = getchar();
printf(“You typed in %c!\n”,num);
printf(“The genie knows all, sees all!\n”);
return(0);
}
Trang 17You can create this source code by editing either GENIE1.C or GENIE2.C Make the necessary modifications and then save the source code to disk
as GENIE3.C
Compile the program Fix any errors that you (hopefully) don’t get Run the result:
I am your computer genie!
Enter a number from 0 to 9:8 You typed in 8!
The genie knows all, sees all!
Run the program again and again with different numbers Hey! That genie knows exactly what you typed! I wonder how that happened? It must be your deftness with the C language Tame that computer!
The problem with GENIE3.C? It doesn’t make a decision The genie isn’t smart at all — it’s just repeating what you already know The purpose behind if, else, and the others is that they allow you to make a decision in your program
Refer to Chapter 10 for more information about the getchar() function
Trang 18What If C==C ?
In This Chapter
Comparing characters with if
Understanding standard input
Fixing the flaws of getchar()
Making a yes-or-no decision
Apologies are in order for the preceding chapter Yes, I definitely drift into
Number Land while introducing the virtues of the if command Computer programs aren’t all about numbers, and the judgment that the if keyword makes isn’t limited to comparing dollar amounts, ecliptic orbits, subatomic particle masses, or calories in various fudgy cookie snacks No, you can also compare letters of the alphabet in an if statement That should finally answer
the mystery of whether the T is “greater than” the S and why the dollar sign is
less than the minus sign This chapter explains the details
I ask you: How can one compare two letters of the alphabet? Truly, this subject is right up there with “How many angels can dance on the head of a pin?” and “Would it be a traditional dance, gavotte, rock, or perhaps heavenly hokey-pokey?”
Yet, comparing letters is a necessary task If you write a menu program, you have to see whether the user selects option A, B, or C That’s done by using the handy if keyword For example:
if(key==’A’)
Trang 19Here, key is a single-character variable holding input from the keyboard The comparison that if makes is to see whether the content of that variable is
equal to (two equal signs) the letter A, which is enclosed in single quotes
This comparison is legitimate Did the user type an A?
To compare a single-character variable with a character — letter, number,
or symbol — you must enclose that character in single quotes Single character, single quotes
When if tests to see whether two things are equal, two equal signs are used Think “is equal to” rather than “equals.”
When you compare a variable — numeric or single character — to a constant, the variable always comes first in the comparison
On a good day, 4.9E3 angels can dance on the head of a pin, given the relative size of the pin and the size of the angels and whether they’re dancing all at once or taking turns
When you compare two letters or numbers, what you’re ‘really comparing are their ASCII code values This is one of those weird instances when the single-character variable acts more like an integer than a letter, number, or symbol
Is the T greater than the S? Alphabetically speaking, yes T comes after S But,
what about the dollar sign and the minus sign? Which of those is greater? And,
why should Q be lesser than U, because everyone knows that U always follows
Q? Hmmm
Computers and math (do I even have
to remind you to skip this stuff?)
with math The computer evolved from the cal
is somehow related to human fingers and thumbs After all, working with numbers is called
computing, which comes from the ancient Latin
term computare That word literally means “hire
a few more accountants and we’ll never truly
Another word for compute is reckon, which is
popular in the South as “I reck’n.” Another word
for compute is figure, which is popular in the
!South (not-South) as “I figure.” Computers reckon Go figure
Sad to say, too much about computers does deal culator, which has its roots in the abacus, which
know what’s going on.”
Trang 20To solve this great mystery of life, I list next the source code for a program, GREATER.C It asks you to enter two single characters These characters are compared by an if statement as well as by if-else The greater of the two
is then displayed Although this program doesn’t lay to rest the head-of-a-pin problem, it soothes your frayed nerves over some minor alpha
angels-on-the-betic conundrums:
#include <stdio.h>
int main() {
char a,b;
printf(“Which character is greater?\n”);
printf(“Type a single character:”);
a=getchar();
printf(“Type another character:”);
b=getchar();
if(a > b) {
printf(“‘%c’ is greater than ‘%c’!\n”,a,b);
} else if (b > a) {
printf(“‘%c’ is greater than ‘%c’!\n”,b,a);
} else { printf(“Next time, don’t type the same character twice.”);
} return(0);
}
Enter the source code for GREATER.C into your editor Make sure that you enter all the proper curly braces, confirm the locations of semicolons, watch your double quotes, and pay attention to the other minor nuances (or nui
sances) of the C language
Save the file to disk as GREATER.C
Compile GREATER.C
Run the final program You’re asked this question:
Which character is greater?
Type a single character:
Trang 21Type a character, such as the $ (dollar sign) Press Enter after typing the
character
Uh-oh! What happened? You see something like this:
Type another character:’$’ is greater than ‘
‘$
What? What? What?
You bet! A problem Right in the middle of the chapter that talks about comparing single-character variables, I have to totally pick up the cat and talk about something else vital in C programming: properly reading single characters from the keyboard
The problem with
Despite what it says in the brochure, getchar() does not read a single char
acter from the keyboard That’s what the getchar() function returns, but it’s
not what the function does
Internally, getchar() reads what’s called standard input It grabs the first char
acter you type and stores it, but afterward it sits and waits for you to type something that signals “the end.”
Two characters signal the end of input: The Enter key is one The second is the EOF, or end-of-file, character In Windows, it’s the Ctrl+Z character In the Unix-like operating systems, it’s Ctrl+D
Run the GREATER program, from the preceding section When it asks for
input, type 123 and then press the Enter key Here’s what you see for output:
Which character is greater?
Type a single character:123 Type another character:’2’ is greater than ‘1’
When you’re first asked to type a single character, you provide standard input for the program: the string 123 plus the press of the Enter key
The getchar() function reads standard input First, it reads the 1 and places
it in the variable a (Line 9 in GREATER.C) Then, the program uses a second
getchar() function to read again from standard input — but it has already been supplied; 2 is read into the variable b (refer to Line 11)