< 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 theif
is 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 thewhile
condition, 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 changinga
orb
, 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 if
andelse
statements are then skipped, and execution continues with the statement after theif-else
group (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 if
andelse
statements are then skipped, and execution continues with the statement after theif-else
group (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 theelse
at the end; this is the block that catches conditions not handled by any of theif
orelse if
conditions. 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 >= b
a <= b
!(a <= b)
a > b
a == b
!(a == b)
a != b
a >= 1 && a <= 10
Since 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 || !b
a || 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
printf
statements would be replaced with code to actually perform the specified option. - The contents of the parentheses following the
switch
must be an integer (orchar
; see next section), and is typically a variable, as shown here, but could also be a mathematical expression. - The
case
keyword must be followed by a constant value (not a variable). - Each
case
statement 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 correctcase
statement, and begins executing code there. (Note that values 0 and 99 both result in printing the exit message.) - The
break
statement at the end of each case causes execution to "break" out of the switch, continuing execution at the statement immediately after theswitch
statement's closing brace. If abreak
statement is eliminated, execution will "fall through" to the next case statement. - The
default
statement is optional, but is a convenient way to handle all values that aren't specifically listed with acase
statement. It is like the finalelse
after a series ofelse if
statements.
Summary
- Braces around a block following an
if
orelse
are optional if there is only one statement in the block. - Use
else if
to make multiple comparisons in a row. - Use logical AND (
&&
) and logical OR (||
) operators to combine Boolean expressions in a conditional expression. - Use
switch
to conveniently and efficiently choose among several values for a variable.
< Previous | Next > |