Professional Documents
Culture Documents
Simple Flow of Control: CSIS1117 Computer Programming
Simple Flow of Control: CSIS1117 Computer Programming
Contents
Selection control
If-statement
Data type -- bool
If/else statement
Dangling else
Logical operators
Short-circuit evaluation
c1117 lecture 3
Statements
c1117 lecture 3
Selection control
int x, y;
cin >> x >> y;
Only execute if the
test expression is true
if( y != 0)
cout << x/y << endl;
if( y == 0)
cout << "The dividend can t be zero" <<
endl;
not equal
c1117 lecture 3
equal
4
if - statement
if(test expression)
body;
c1117 lecture 3
c1117 lecture 3
!= means
NOT equal
Block statement
// This is wrong !!
if(y == 0)
cout << "The dividend can t be zero" <<
endl;
cout << "
^^^^^^^^ " << endl;
c1117 lecture 3
// This is correct!
if(y == 0){
cout << "The dividend can t be zero" << endl;
cout << "
^^^^^^^^ " << endl;
}
if/else statement
int x, y;
cin >> x >> y;
if( y != 0)
cout << x/y << endl;
if( y == 0){
cout << "The dividend can t be zero" <<
endl;
c1117 lecture 3
11
if/else statement
Execute if the test
expression (y==0) is true
int x, y;
cin >> x >> y;
if( y == 0){
cout << "The dividend can t be zero" <<
endl;
c1117 lecture 3
12
13
Are they the same? Which one will give the wrong
answer?
c1117 lecture 3
14
if x = 10
is a positive even number
if x = 7
is a non-positive
number
positive
even number";
else
cout << "It is a non-positive number";
15
if (x > 0){
if (x % 2 == 0)
cout << "It is a positive even number";
}else
cout << "It is a non-positive number";
See checking.cc
c1117 lecture 3
16
1994
<< endl;
17
How about
1900
But it is divisible by 4 !!
A leap year is divisible by 4, but not divisible by
100
18
How about
2000
But it is divisible by 4 and 100 !!
c1117 lecture 3
19
c1117 lecture 3
20
Logical operators
If your exam score is at least 70 and less than 75, you get a
B+
If you fail in the quiz or exam, you will receive a warning letter
c1117 lecture 3
21
<< endl;
Simplified to
cin >> mark;
if (mark >= 70 && mark < 75)
cout << You get a B+ << endl;
c1117 lecture 3
22
Common mistakes:
c1117 lecture 3
23
Operator Precedence
highest
priority
*, /, %
+,
lowest
Logical NOT
Binary operators
Relational
operators
Logical AND
Logical OR
24
c1117 lecture 3
25
Short-circuit evaluation
No!! They are not the same, the second one will
give error if count is zero.
Why?
c1117 lecture 3
26
Short-circuit evaluation
c1117 lecture 3
27
Short-circuit evaluation
It is evaluated first, if it is false, the second subexpression (scores/count<60) is not evaluated.
if(count != 0 && scores / count < 60)
cout << "low average warning" << endl;
if(scores / count < 60 && count != 0)
cout << "low average warning" << endl;
28
Conditional operator
See conditional-op.cc
c1117 lecture 3
29