Selection Structures: CSE115: Computing Concepts
Selection Structures: CSE115: Computing Concepts
Selection Structures
CSE115: Computing Concepts
The if Statement – One Alternative
The if Statement – One Alternative
• if Statement (One Alternative)
• FORM: if( condition )
statement T ;
• INTERPRETATION: If condition evaluates to true (a nonzero
value), then statement T is executed; otherwise, statement T is
skipped.
• EXAMPLE:
if (x != 0)
product = product * x;
The if Statement – Two Alternatives
The if Statement – Two Alternatives
• if Statement (Two Alternatives)
o FORM: if( condition )
statement T ;
else
statement F ;
o INTERPRETATION: If condition evaluates to true ( a nonzero value), then
statement T is executed and statement F is kipped; otherwise,
statement T is skipped and statement F is executed.
• EXAMPLE:
if (rest_heart_rate > 56)
printf("Keep up your exercise program!\n");
else
printf("Your heart is in excellent health!\n");
The if Statement – Two Alternatives
#include <stdio.h>
int main()
{
int pulse; /* resting pulse rate for 10 secs */
int rest_heart_rate; /* resting heart rate for 1 minute */
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
printf("It’s an odd number");
printf("It’s an even number");
if (item % 2 == 1);
printf("It’s an odd number");
printf("It’s an even number");
if (item % 2 == 1)
printf("It’s an odd number");
printf("It’s an even number");
if (item % 2 == 1)
printf("It’s an odd number");
else
printf("It’s an even number");
if Statements with Compound True or False Statements
• Example:
int a = (2 > 3);
int b = (3 > 2);
• 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)
{
printf("Wet roads ahead\n");
printf("Stopping time doubled\n");
}
else
{
printf("Icy roads ahead\n");
printf("Stopping time quadrupled\n");
}
}
else
printf("Drive carefully!\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