To really use the power of the C language, your programs need to make decisions. A computer can't think, but it can make comparisons, evaluate the results of the comparisons, and then act on that information. The if keyword is used in C programming to make comparisons and control the flow of your program.
The if keyword is used in C to make a comparison: A variable is compared to a value, or two variables are compared to each other. If the result of that comparison is true, one or more statements are executed. If the comparison is false, the statements are skipped over like a three-month-old box of Chinese take-out in the back of your refrigerator.
In English, the if comparison looks like this:
if(I_am_hungry == yes)
{
go_to(kitchen);
snack = make(food);
eat(snack);
}
if is followed by a comparison in parentheses. This is a mathematical comparison. The operators shown in the following table are used for comparing the values of two variables or the values of one variable and an immediate value.
Operator | Meaning | Example |
---|---|---|
== | Is equal to | decade == 10 |
< | Is less than | negative < 0 |
> | Is greater than | century > 100 |
<= | Less than or equal to | little_kid <= 12 |
>= | Greater than or equal to | millionaire >= 1000000 |
!= | Not equal to | odd != 2 |
No semicolon follows the if statement's parentheses.
Following the parentheses is one or more statements, enclosed in braces. Those statements are executed only if the condition (in parentheses) is true. If the condition is false, the statements are skipped. The next statement, following if's final brace, is then executed.
Most of the operators in the table should be familiar to you from elementary school math class. Note however, that an equal comparison is done with two equal signs, not one. Also, "less than or equal to" is written as it's pronounced: <= and not =<; ditto for "greater than or equal to," which cannot be written =>.
Not-equal is written !=. The character for not in the C language is the exclamation point. (This topic pops up elsewhere as you find out more about C.) As with less-than-or-equal-to and greater-than-or-equal-to, not-equal must be written != and not =!.
It helps to remember == for a comparison if you pronounce it "is equal to" and not "equals." The single equal sign, =, is used in C for assignment.
dummies
Source:http://www.dummies.com/how-to/content/how-to-construct-a-basic-if-statement-in-c.html
No comments:
Post a Comment