4 Selection
4 Selection
return 0;
}
The if Statement – Two Alternatives
Look for Bugs!!!
• If the variable item is even, print “It’s an even number”,
otherwise print “It’s an odd number”
if item % 2 == 1
compilation
printf("It’s an odd number");
error
printf("It’s an even number");
if (item % 2 == 1);
logical
printf("It’s an odd number");
error/bug
printf("It’s an even number");
if (item % 2 == 1)
logical
printf("It’s an odd number");
error/bug
printf("It’s an even number");
if (item % 2 == 1)
printf("It’s an odd number"); correct
else code
printf("It’s an even number");
if Statements with Compound True or False Statements
• Example:
int a = (2 > 3);
int b = (3 > 2);
a = 0; b = 1
Truth Values
• Be careful of the value returned/evaluated by a relational
operation.
• Since the values 0 and 1 are the returned values for false and
true respectively, we can have codes like these:
int a = 12 + (5 >= 2); // 13 assigned to a
int b = (4 > 5) < (3 > 2) * 6; // 1 assigned to b
int c = ( (4 > 5) < (3 > 2) ) * 6; // 6 assigned to c
A B A && B A || B !A
int x, a = 4, b = -2, c = 0;
x = (a > b && b > c || a == b);
expr1 && expr2: If expr1 is false, skip evaluating expr2, as the result
will always be false.
Nested if Statements
• An if statement with another if statement as its true task
or its false task
Nested if Statements
if (road_status == 'S')
if (temp > 0)
else
printf("Icy roads ahead\n");
Nested if Statements
Multiple-Alternative Decision Form of Nested if
• SYNTAX:
if ( condition 1 )
statement 1
else if ( condition 2 )
statement 2
.
.
.
else if ( condition n )
statement n
else
statement e
Multiple-Alternative Decision Form of Nested if