| < Previous |
More on Conditionals |
Next > |
Conditionals are used in if and while expressions.
This section covers some additional important features for conditionals.
Note that the examples below are code fragments; you will need to put them
inside your main() function.
- In the case where there is only one statement in a block following
an
if, the braces are optional and can be omitted.
if (a < b)
printf("a is smaller!\n");
When an if's condition is true, the computer will execute
the (one) statement immediately following the if. In order to
execute multiple statements, they are combined into a block (multiple
statements in braces); the block is considered a single statement. This
applies to all conditionals, e.g. else, else if
(below), while, and for (explained in the next
section).
if
or while condition? The computer identifies the semicolon as an
empty statement. Consider the following examples -- the erroneous semicolon
is marked in red.
if (a < b); printf("boo!"); while (a < b); { // some code here... a = a + 1; }
- In the first example, when the
if's condition is true, the statement following theifis executed -- this is the semicolon / empty statement! So, "boo!" will always be printed. (Note that code indentation is ignored by the compiler.) - The second example is an excellent illustration of an infinite loop.
If the condition (
a < b) is true, execution will move to the statement following thewhilecondition, in this case the empty statement specified by the semicolon. After executing that statement (doing nothing), execution returns to the condition. But, since nothing is changingaorb, the condition will never become false, and execution will never leave the loop!
else case following
an if, you can use the "else if" clause.
When the condition of the if is false, the condition
of the else if will be checked. If it is true, the block
(or statement) following it will be executes; if the else if's
condition is false, the block will be skipped, and execution will continue
after it.
if (score >= 90)
printf("you got an A\n");
else if (score >= 80)
printf("you got a B\n");
else if (score >= 70)
printf("you got a C\n");
else
printf("better luck next time!\n");
printf("done...\n");
Some examples using the above code:
score = 95: theif's condition is true, so its statement is executed (the "A" message is printed). The remainingelse ifandelsestatements are then skipped, and execution continues with the statement after theif-elsegroup (the "done" message).score = 85: theif's condition is false, so execution moves to the (first)else if. That condition is true, so its statement is executed (the "B" message is printed). The remainingelse ifandelsestatements are then skipped, and execution continues with the statement after theif-elsegroup (the "done" message).score = 65: theif's condition is false, so execution moves to the (first)else if. Its condition is false, so execution moves to the secondelse if(comparing score to 70). That is also false, so execution moves to theelseat the end; this is the block that catches conditions not handled by any of theiforelse ifconditions. It prints the "better luck" message, then execution continues with the "done" message.
&& for a logical AND,
and || for a logical OR. Note that both operands must
be complete Boolean expressions.
if (age >= 13 && age <= 19)
printf("you are a teenager\n");
if (age < 10 || age >= 65)
printf("you get a discount\n");
!) will negate an expression, turning a true
expression false, or a false expression true.
Expression Opposite Opposite Simplified a < b!(a < b)a >= ba <= b!(a <= b)a > ba == b!(a == b)a != b
a >= 1 && a <= 10Since we want to check the opposite, we need to negate the expression:
!(a >= 1 && a <= 10)While we could use the expression above, it's better to resolve the NOT and use a simpler expression. Here are the rules for negating expressions that use logical AND and logical OR:
So, our expression becomes:
Expression Opposite Opposite Simplified a && b!(a && b)!a || !ba || b!(a || b)!a && !b
!(a >= 1) || !(a <= 10)Recall from above how to find the opposite of an inequality, which simplifies our expression to:
a < 1 || a > 10
if (a < 1 || a > 10)
printf("Bad value!");
else if statements (starting with if and possibly
ending with else). But, a better way is to use a switch
statement. One common example is a menu, where the program displays a list
of options, and the user enters a number to select what the program should
do.
switch (a)
{
case 1:
printf("option 1...");
break;
case 2:
printf("option 2...");
break;
case 3:
printf("option 3...");
break;
case 0:
case 99:
printf("exiting...");
break;
default:
printf("unknown option!");
break;
}
- In this example, the
printfstatements would be replaced with code to actually perform the specified option. - The contents of the parentheses following the
switchmust be an integer (orchar; see next section), and is typically a variable, as shown here, but could also be a mathematical expression. - The
casekeyword must be followed by a constant value (not a variable). - Each
casestatement must list a single value; it cannot specify a range. - When the program runs, it looks at the value of variable
a, jumps to the correctcasestatement, and begins executing code there. (Note that values 0 and 99 both result in printing the exit message.) - The
breakstatement at the end of each case causes execution to "break" out of the switch, continuing execution at the statement immediately after theswitchstatement's closing brace. If abreakstatement is eliminated, execution will "fall through" to the next case statement. - The
defaultstatement is optional, but is a convenient way to handle all values that aren't specifically listed with acasestatement. It is like the finalelseafter a series ofelse ifstatements.
Summary
- Braces around a block following an
iforelseare optional if there is only one statement in the block. - Use
else ifto make multiple comparisons in a row. - Use logical AND (
&&) and logical OR (||) operators to combine Boolean expressions in a conditional expression. - Use
switchto conveniently and efficiently choose among several values for a variable.
| < Previous | Next > |