05 Selection
05 Selection
Algebraic equality or
C relational operator Sample C condition Meaning of C condition
relational operator
= == x == y x is equal to y
≠ != x != y x is not equal to y
Relational Operators
• The relational operators are <, >, <=, and >=.
• Take 2 expressions as operands
• Yield either the int value 0 (false) or the int value 1 (true).
• The expressions
• a == b is a test for equality.
• a = b is an assignment expression
Logical Operators
• logical expression: an expression that uses one or more of the logical
operators
• && (and)
• || (or)
• ! (not)
Logical Operators
• Expressions connected by && or || are evaluated left to right.
• logical complement (negation):!
• the complement of a condition had the value 1 (true) when the condition’s
value is 0 (false)
• the complement of a condition has the value 0 (false) when the condition’s
value is nonzero (true)
Logical Operators
Expression Value
!5 0
!!5 1
!(6 < 7) 0
!6 < 7 1
!(3-4) 0
Selection Statements in C
making decisions
The if Selection Statement
• Selection statements choose among alternative courses of action
• If student’s grade is greater than or equal to 60
Print “Passed”
• If true, then “Passed” is printed
• If false, the printing is ignored
• Written in C as
if (grade >= 60) { // grade must be declared before this
printf("Passed");
} // end if
• The C if statement code corresponds closely to the pseudocode
The if Selection Statement
• Indentation in the if Statement
• The indentation in the second line is optional but highly recommended
• Emphasizes the inherent structure of structured programs
• The compiler ignores white-space characters used for indentation and vertical
spacing
• blanks, tabs and newlines
The if Selection Statement
The if…else Selection Statement
• Specifies different actions to perform when the condition is true or
false
• 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
• Otherwise, it prints “Failed”
• The else’s body also is indented
The if…else Selection Statement
• Written in C as