Chapter 3-Selection Structures in C-PreClass
Chapter 3-Selection Structures in C-PreClass
Structured Program
Development in C
...
if ( grade >= 60 ) {
printf( "Passed\n" );
} // end if
...
• The if…else selection statement allows you to specify that different actions
are to be performed when the condition is true and when it’s false.
• For example, the pseudocode statement
If student’s grade is greater than or equal to 60
Print “Passed”
else
Print “Failed”
prints Passed if the student’s grade is greater than or equal to 60 and Failed if the student’s
grade is less than 60.
• In either case, after printing occurs, the next pseudocode statement in
sequence is “performed.” The body of the else is also indented.
...
int a = 15
int b = 10
if ( a = b ) {
printf( ”%d is equal to %d\n", a, b);
} // end if
else {
printf( ”%d is not equal to %d\n", a, b);
} // end else
...
• The conditional operator is C’s only ternary operator—it takes three operands.
• These together with the conditional operator form a conditional expression.
• The first operand is a condition.
• The second operand is the value for the entire conditional expression if the condition is
true and the third operand is the value for the entire conditional expression if the
condition is false.
if ( grade >= 90 )
puts( "A" );
else
if ( grade >= 80 )
puts("B");
else
if ( grade >= 70 )
puts("C");
else
if ( grade >= 60 )
puts( "D" );
else
puts( "F" );
• If the variable grade is greater than or equal to 90, all four conditions will be true, but
only the puts statement after the first test will be executed.
• After that puts is executed, the else part of the “outer” if…else statement is skipped.
• In this case, if grade is less than 60, the program executes both puts
statements in the body of the else and prints
Failed.
You must take this course again.
• The braces surrounding the two statements in the else are important.
Without them, the statement
puts( "You must take this course again." );
would be outside the body of the else part of the if and would execute
regardless of whether the grade was less than 60.
a higher
int age = 21;
if ( age = 22 ) {
b lower printf( "higher\
n" );
} // end if
c It has compile-time error.
else {
printf( "lower\
d No output will generate. n" );
} // end else
Quiz Result
a Yes
int age = 21;
if ( age++ == 22 ) {
b No printf( ”Yes\n" );
} // end if
else {
c It has compile-time error.
printf( ”No\n" );
} // end else
d No output will generate.
Quiz Result