Download as pdf or txt
Download as pdf or txt
You are on page 1of 29

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

So far, we have learned to write simple programs,


which can interact with users.
However, in many cases, we want some
statements to be executed only if certain criteria
are satisfied.

e.g. we need to check if y is zero to prevent the run time


error.
We will have
int x, y;
an runtime
cin >> x >> y;
error if y=0
cout << x/y << endl;

c1117 lecture 3

Selection control

The problem can be solved by attaching a test


expression (condition). If the condition is true, the
statement is executed. Otherwise, the statement
is skipped.
Test expression

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;

We can use an if-statement to determine whether


certain code is required to execute.
An if-statement consists of a test expression that
evaluates to true or false and the body.
The body (consequence) will be executed only if
the test expression is true.
See cal-div.cc as an example

c1117 lecture 3

Data type -- bool

We ve discussed the data type int, double, and


string, they use to represent different values.

int: 7, -3, 1000, etc


double: 1.2, -3.45, 0.012, etc
string: "Peter", "Hello World!", etc

bool only for storing true or false value.


Test expression has the value of type bool.
bool isZero = (y == 0);

c1117 lecture 3

A test expression is usually formed by comparing


two numbers with Relational Operator.

e.g. a>b, a>=b, a<=b, a<b, a==b, a!=b


== means
equal

!= means
NOT equal

bool isZero = (y == 0);


if(isZero)
cout << "The dividend can t be zero"
<< endl;
Equal to:
if(isZero == true)
c1117 lecture 3

Block statement

Suppose now we want to print two lines if y is zero.

// This is wrong !!
if(y == 0)
cout << "The dividend can t be zero" <<
endl;
cout << "
^^^^^^^^ " << endl;

This statement is executed independent


of the result of the test expression

Note that the body of an if-statement is a single


statement.

c1117 lecture 3

We can group one or more statements to form a


block statement delimited by a pair of braces.

A block statement is a single statement.


We can even declare variables inside a block
No need to put a semi-colon after a block.

// This is correct!
if(y == 0){
cout << "The dividend can t be zero" << endl;
cout << "
^^^^^^^^ " << endl;
}

Specifying a block statement


c1117 lecture 3

if/else statement

Sometimes we want the program to choose only


one of two alternatives.

int x, y;
cin >> x >> y;
if( y != 0)
cout << x/y << endl;
if( y == 0){
cout << "The dividend can t be zero" <<

endl;

cout << "


}
c1117 lecture 3

^^^^^^^^ " << endl;

No matter what value of y, only one


of the bodies is executed.
10

The two alternatives are mutually exclusive, the


input number y is either equal to zero (y==0) or
not equal to zero (y!=0), but not both.
Using if/else-statement can represent this idea
naturally and more clearly.

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;

cout << "


^^^^^^^^ " << endl;
}else
cout << x/y << endl;

Execute if the test expression is false

See cal-div-else.cc as an example

c1117 lecture 3

12

More on test expression

A test expression can be formed by comparing two


values.
//
//
(x
(x
(x

Examples on test expressions


x, y and z are numbers
>= y);
+ z > y);
+ z > y * z);

Arithmetic expression also has a value, it will


be evaluated before the comparison.
c1117 lecture 3

13

Dangling else problem


Consider the following two programs:
if (x > 0)
if (x % 2 == 0)
cout << "It is a positive even number";
else
cout << "It is a positive odd number";
if (x > 0)
if (x % 2 == 0)
cout << "It is a positive even number";
else
cout << "It is a non-positive number";

Are they the same? Which one will give the wrong
answer?
c1117 lecture 3

14

Dangling else problem


// if x = 10
It is a positive even number
if (x > 0)
// if x = 7
if (x % 2 == 0)
is a positive
odd number
cout << "It is It
a positive
even number";
else
cout << "It is a positive odd number";
//
It
if (x > 0)
//
if (x % 2 == 0)
cout << "It is It
a

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";

The second program give wrong answer, why?


c1117 lecture 3

15

An else is always matched with the nearest


preceding unmatched if.
We need to use parentheses to indicate the else
for the outer if.

So the second program should be modified as follow:

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

Example leap year

Write a program to determine whether a year is a


leap year.
How to check if a year is a leap year?
1997
1996
A leap year is divisible by 4

1994

cin >> year;


if (year % 4 == 0)
// may be a leap year
else
cout << "It is not a leap year
c1117 lecture 3

<< endl;
17

Example leap year

How about

1900
But it is divisible by 4 !!
A leap year is divisible by 4, but not divisible by
100

cin >> year;


if (year % 4 == 0){
if (year % 100 == 0)
// may not be a leap year
else
cout << "It is a leap year" << endl;
}else
cout << "It is a not a leap year" << endl;
c1117 lecture 3

18

Example leap year

How about

2000
But it is divisible by 4 and 100 !!

A leap year is divisible by 4, but not divisible by


100. However, if it is divisible by 400, it is still a
leap year.

c1117 lecture 3

19

Example leap year


cin >> year;
if (year % 4 == 0){
if (year % 100 == 0){
if (year % 400 == 0)
cout << "It is a leap year" << endl;
else
cout << "It is not a leap year" <<
endl;
}else
cout << "It is a leap year" << endl;
}else
cout << "It is not a leap year" << endl;

See leap-year.cc and leap-year-bool.cc

c1117 lecture 3

20

Logical operators

A test expression sometimes consists of other subexpressions , e.g.

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

Test expressions can be combined using logical


operators, e.g. && (AND), || (OR) and ! (NOT).

A logical operator applies on bool values and the result is


also of type bool.

c1117 lecture 3

21

We can simplify the program code by using Logical


operator.
cin >> mark;
if (mark >= 70)
if (mark < 75)
cout << You get a B+

<< endl;

Simplified to
cin >> mark;
if (mark >= 70 && mark < 75)
cout << You get a B+ << endl;
c1117 lecture 3

22

Note that a range condition, such as a<= x < b,


has to be written in forms like (a<=x)&&(x<b)

See range.cc and range-logical.cc

Common mistakes:

Mixing = with == , | with || and & with &&


These logical errors are difficult to detect as they cannot
be reported by the compiler.
See misuse.cc

c1117 lecture 3

23

Operator Precedence
highest

priority

*, /, %
+,

lowest

<, <=, >, >=


==, !=
&&
||

Logical NOT
Binary operators
Relational
operators
Logical AND
Logical OR

You can use parentheses to force the order of evaluation.


c1117 lecture 3

24

Add parentheses to the following expressions to


show the precedence of the computation.
x + 3 >= 9 || z != x * 2 && !(y / 2 < 3)

( ((x + 3 ) >= 9 ) || ((z != (x * 2 ))&&


(! (y / 2 ) < 3 )))

c1117 lecture 3

25

Short-circuit evaluation

are the following programs the same?


if(count != 0 && scores / count < 60)
cout << "low average warning" << endl;
if(scores / count < 60 && count != 0)
cout << "low average warning" << endl;

No!! They are not the same, the second one will
give error if count is zero.
Why?
c1117 lecture 3

26

Short-circuit evaluation

Sub-expressions in test expression are not


evaluated if the value of the entire expression is
already known.

E.g. A test expression (expr1) && (expr2) is false if at


least one of expr1 and expr2 is false. Therefore, if the
expr1 is known to be false, the expr2 will not be
evaluated as the result of the entire expression is known
after evaluating expr1.

The short-circuit feature is useful in simplifying


some program code. However, you need to
consider the order of the sub-expressions

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;

If count is zero, this sub-expression will cause


run time error.
c1117 lecture 3

28

Conditional operator

This is the only ternary operator in C++.


Syntax
expr0 ? expr1 : expr2

If expr0 is evaluated to true,

Evaluate expr1 to be the value of the whole expression


Otherwise, evaluate expr2 to be the value of the whole
expression.

Since it is an expression, it can appear inside a


statement.

See conditional-op.cc

c1117 lecture 3

29

You might also like