Lecture3 CSE1201
Lecture3 CSE1201
Dr Khaleda Ali
[email protected]
CHAPTER OBJECTIVES
To become familiar with the three kinds of control structures: sequence,
selection, and repetition
To understand compound statements
To learn how to compare numbers and characters
To learn how to use the relational, equality, and logical operators to write
expressions that are true or false
To learn how to write selection statements that choose between two
alternatives in a program using the if statement
To learn how to implement decisions in algorithms using the if statement
To understand how to select among more than two alternatives by nesting if
statements
To learn how to use the switch statement as another technique for selecting
among multiple alternatives
2
Control Structures
6
Conditions
Relational Operators Practice
7
Conditions
Logical Operators
we can form more complicated conditions or logical expressions.
Operators Meaning
&& And
|| Or
! Not
8
Conditions
Logical AND operator && (double ampersand)
The condition evaluates to TRUE if and only if BOTH expressions on either
side of && evaluate to TRUE Otherwise condition evaluates to FALSE
Note operator precedence
Beware of ‘short circuit evaluation’
Make the condition most likely to be FALSE the left-most condition
9
Conditions
Logical OR operator || (double vertical bar)
The condition evaluates to TRUE if one or the other or both expressions on
either side of || evaluate to TRUE
Note operator precedence
Otherwise condition evaluates to FALSE
Beware of ‘short circuit evaluation’
Make the condition most likely to be TRUE the left-most condition
10
Conditions
Logical NOT operator ! (exclamatory sign)
The condition evaluates to TRUE if expressions after ! evaluate to FALSE
Note operator precedence (An operator’s precedence determines its order of
evaluation)
Otherwise condition evaluates to FALSE
11
Example
Slide 12
Short circuit evaluation
C evaluates only part of the expression. An expression of the form a || b
must be true if a is true. Consequently, C stops evaluating the expression
when it determines that the value of !flag is 1 (true). This technique of
stopping evaluation of a logical expression as soon as its value can be
determined is called short-circuit evaluation .
We can use short-circuit evaluation to prevent potential run-time errors.
Slide 13
Conditions
Comparing characters
We can also compare characters in C using the relational and equality operators.
Expression Value
‘9’ > ‘0’ 1 (true)
‘a’ < ‘e’ 1 (true)
‘B’ <= ‘A’ 0 (false)
‘a’ <= ch && ch <= 1 (true) if ch is a lowercase
‘z’ letter
14
The if Statement
17
Nested if Statements
evencount = oddcount = 0;
if ( (num % 2) == 0 )
{
printf(“%d is an even number.\n”, num);
An if statement that is nested ++evencount;
18