You are on page 1of 40

EE1005 From Computational

Thinking to Programming

Lesson 6
Decision Making
(Reference: Harry H. Cheng, Chapter 5)

Dr. Tan Chee Wah, Wesley (CoPaCE/School of EEE)


Email: wesleytan@ntu.edu.sg
Office: S1-B1b-54
Phone: 6790 6009

“Be Prepared, Give Feedback”


Three Basic Program Structures
1. Sequence
Statements are executed line by line in
sequential order.
2. Selection
Sequence of program execution may be altered
based on some conditions.
3. Repetition
A group of statements is repeated a certain
number of times.

6-2
Relational Operators

In programming, we frequently need to check


expressions to see whether they are true or not.
If true, the program flow follows one path, and if
false, it follows another path.
For example:
Is exam_mark greater than 80?
If say exam_mark = 70, result of evaluating the
above returns False. Other examples:

Is getchar() == '\n' ?
Does the integer n lie in the interval
6-3
[0,10]?
Relational Operators in C

> Greater than


>= Greater than or equal to
< Less than
<= Less than or equal to
== Equal to
!= Not equal to

We will use the above operators in


expressions, for checking whether
they return True or False. 6-4
Example:

An expression containing a relational operator


returns value 1 (TRUE) or 0 (FALSE).

For real x; x*x >= 0 is always true.


The C expression (x*x >= 0) returns a value 1!

x = -5;
printf("The expression x*x >= 0 has value
%d", x*x>=0);

Returns a value 1! 6-5


Example (Continued):
Output:

The expression x*x >= 0 has value 1


------------------------------------
On the other hand,
printf("The expression x*x < 0 has
value %d", x*x<0);
Output:
The expression x*x < 0 has value 0
6-6
x*x < 0 is always False (0)
Note:
Do not confuse == (equality) with = (assignment)
a==b Checks whether values of a and b are equal.
a=b Value of b is assigned to a. There is change
of data in variable a.

Suppose a = 1, b = 5
printf("The value of a==b is %d", a==b);
a==b is False (0)
printf("The value of a=b is %d", a=b);
a=b = 5 6-7
Note:
In C, any non-zero numeric value can also
represent TRUE.
Example:
a = 15;
if (a) printf("%d", a);

As a is not zero (which means TRUE),


printf() will be executed.
If a is 0 (which means FALSE), printf() will
not be executed.
6-8
Note:

Suppose we write the statement as


if (a = 15) printf("%d", a);

Interpretation:
Return value of expression (a = 15) is 15.
Result of (a = 15) is TRUE (non-zero).
printf() will be executed.

6-9
Note:
What will be shown on screen after running:
int a = 15;
if (a = 0) printf("%d\n", a);

a is set to zero (FALSE) so printf() will


NOT be executed
if (a == 0) printf("%d\n", a);

a is set to zero in the previous


statement. Now (a==0) is TRUE so
printf() will be executed
6-10
Remark on the Example about isdigit()
For Slide 5-24, Original Form:

char ch='1';
if (isdigit(ch) != 0) //isdigit() is TRUE (non-
zero)
printf("%c is a digit.", ch);
else
printf("%c is not a digit.", ch);

Simpler Form:

if (isdigit(ch)) //isdigit() is TRUE (non-zero)


printf("%c is a digit.", ch);
else
printf("%c is not a digit.", ch);
6-11
Comparing Characters

Characters can be compared using relational


operators.

Is 'B' > 'A'?


Is '1' > 'A'?
Basis for comparison?
Using characters’ ASCII values (slide 3-
17)

6-12
Example

Expression Value

'9' >= '0' 1 (TRUE)


(57) (48)
'B' <= 'A' 0 (FALSE)

'A' <= 'a' 1 (TRUE)


(65) (97)
'a' <= '$' 0 (FALSE)
6-13
Logical Operators (&&, ||, !)

AND, OR, NOT

Symbols && || !
These are needed to form complex conditions.
They enhance the decision-making capabilities
of our C programs.

&& and || are binary operators because they


act on 2 expressions.

! is unary (act on 1 expression).


6-14
Examples

(temperature > 90.0) && (humidity > 0.9)


(x >= 1) || (x < 0)
(x >= 1) && (x < 0)
- Is it possible that x is greater than or equal
to 1 AND less than 0 at the same time?
!((x >= 1) && (x < 0))
('A' <= ch) && (ch <= 'Z')
- Check whether value of ch is between [A, Z]
6-15
Truth Values and Truth Table
The truth value (True or False) of a logical
expression is determined by a Truth Table. In
the table below, P and Q are relational
expressions.

P Q P && Q P || Q !P
F F F F T
F T F T T
T F F T F
T T T T F
6-16
Logical Assignment
We may even assign return value (either 0 or 1)
of logical expressions evaluation to variables.
even = (n%2 == 0);
- (n%2 == 0)returns true (1) if n divided by 2
gives zero remainder
in_range = (n > -10 && n < 5);
- (n > -10 && n < 5) returns true (1) if n is
between -10 and 5, excluding -10 and 5
is_letter = ('A' <= ch && ch <= 'Z') || ('a'
<= ch && ch <= 'z');
- Above returns true (1) if ch is an alphabet
6-17
i.e. ch is within [A, Z] or [a, z]
More about the if statement

if (expression)
{
statement_1;
.......
statement_n;
}

As we have seen in Lesson 2, if expression is true,


the statement block within {} is executed. Otherwise,
the block is skipped.
If there is only 1 statement to be executed, {} can be
excluded i.e. we can just write
if (expression) 6-18
statement_1;
Program 6.1 (Quadratic Equation)

a*x*x + b*x + c = 0
Program 2.4 (Slide 2-27 and 28) fails if the user
enters 0 for the coefficient a.
We should test for a non-zero value of a given by
the user.
if (a != 0) //can be written as if (a)
{ root1 = (-b + sqrt(b*b-4*a*c))/(2*a);
root2 = (-b - sqrt(b*b-4*a*c))/(2*a);
}
6-19
The else clause
The if structure is very frequently used with the
optional else:
if (expression)
{ . . . . . . .
}
else
{ . . . . . . .
}
If there is only 1 statement to be executed, {} can be
excluded i.e. we can just write
if (expression)
one_statement;
else 6-20
another_one_statement;
Program 6.2 (quadratic equation)

if (a == 0) //if a is zero, only 1 root


{
printf("You input a = 0.\n");
printf("Only one root: %8.3f", -c/b);
}
else //else if a is non-zero, there
will be 2 root values
{ root1 = (-b + sqrt(…))/(2*a);
. . .
}
6-21
Refinements

How do you handle the following situations?

• a = 0 and b = 0, but c not 0


• a = b = c = 0
A good program must take into account these
possibilities (or all possibilities).

6-22
Nested if statements

These are if statements that contain other if


statements.
In the quadratic equation problem, what if

b*b - 4*a*c < 0 ?


We’ll use a nested if to deal with this.

6-23
Program 6.3 Brown if-else
statements
if (a == 0) { . . .} are NESTED
within Black
else if-else
{ statements
if (b*b-4*a*c < 0)
printf("Complex roots.\n")
else //2 real roots
{
root1 = (-b + sqrt() . . .);
. . .
}
6-24
}
Give it a Try Yourself!
Modify Program 6.3 so that it appears to be
capable of handling complex roots. How?
A little cheating!
Suppose the complex roots are

α + iβ, α - iβ
Compute α and β separately, and in the output
insert the strings “+ i” and “- i”.

6-25
if..else if..else if..
Program Fragment 6.4:

if (quiz_mark >= 80) //if mark is 80 or


higher
grade = 'A';
else //else if mark is 70 or higher, but
lower than 80
if (quiz_mark >= 70)
grade = 'B';
else //else if mark is 60 or higher,
but lower than 70
if (quiz_mark >= 60)
grade = 'C';
6-26
else . . .
An Equivalent Form

if (quiz_mark >= 80)


grade = 'A';
else if (quiz_mark >= 70)
grade = 'B';
else if (quiz_mark >= 60)
grade = 'C';
else if
. . .
6-27
Review
• Rewrite the Program 6.4 so that the program
tests for 'F' grade (quiz_mark<50) first, then
'D' (50≤quiz_mark<60), etc.
• Question: Suppose we rewrite Program
Fragment 6.4 using separate if statements:
if (quiz_mark >= 80) grade = 'A';
if (quiz_mark >= 70) grade = 'B';
if (quiz_mark >= 60) grade = 'C';
. . . . . .
Are the 2 ways of writing equivalent? 6-28
Discussion
• The 2 ways of writing are different!
•For the original Program 6.4 on slide 6-26 or
27, once a condition is satisfied (TRUE),
evaluation will STOP!
•E.g. by assigning 75 to quiz_mark in the
beginning, the first if-statement for
(quiz_mark >= 80) will be evaluated. This will
return FALSE.
•Next, (quiz_mark >= 70) will be evaluated.
This returns TRUE, so grade = 'B', and
program will JUMP OUT of the if-else if-else if…
statements. 6-29
Discussion
• Consider now the separate if-statements. Each
if-statement WILL be evaluated regardless of the
value of quiz_mark. Using quiz_mark = 75 again,
if (quiz_mark >= 80) grade = 'A';
- returns FALSE so grade is not assigned
if (quiz_mark >= 70) grade = 'B';
- returns TRUE so grade is B
if (quiz_mark >= 60) grade = 'C';
- returns TRUE also so grade is now C
- if this is the last if-statement, grade
is ‘C’, not ‘B’! 6-30
Program 6.5

Purpose: To construct a menu of choices, which


looks like the following:

Select the form of Ohm’s Law:


[A] Voltage [B] Current [C] Resistance
Your Selection (A, B, C) =>

6-31
Program 6.5 (Continued)

char selection;
printf("Select form of Ohm’s Law.\n");
printf("[A] V, [B] I, [C] R \n");
printf("Your selection => ")
scanf("%c", &selection);
// user’s choice will be stored in
variable selection

6-32
Program 6.5 (Continued)
if (selection == 'A')
printf("V = I*R");
else if (selection == 'B')
printf("I = V/R");
else if (selection == 'C')
printf("R = V/I");
else
printf("Wrong selection");
6-33
The switch statement
Too many if-else statements can be confusing.
In this case, we may use the switch statement.
switch (expression)
{ case value_1: statement(s)
case value_2: statement(s)
. . . . . .
case value_n: statement(s)
default: statement(s)
} 6-34
The switch statement (Continued)
The expression MUST return an integer
(including char) value.
The computer compares this returned value
against the value following each case label, i.e.
value_1, value_2...

• If there is a match, the statement(s) following


the case label will be executed.
• If no match at all, the statement(s) following
the default label (optional) will be executed.
• If there is no match and no default label, then
exit statement block for switch.
6-35
The break statement

If a match is found, the remaining cases WILL


be executed, without the case values being
checked unless there is a break statement (See
Program 6.6a).

Thebreak statement is used to exit from the


switch structure (See Program 6.6b).

6-36
Program 6.6a (without ‘break’)
switch (selection)
{case 'A': printf("V = I*R");
//selection=‘B’ does not match ‘A’ so printf()is
not executed
case 'B': printf("I = V/R");
//selection=‘B’ matches ‘B’ so I = V/R is printed
case 'C': printf("R = V/I");
//once a match is found, statement R = V/I will be
printed
default: printf("Wrong selection.");
//once a match is found, statement Wrong
selection. will be printed
}
If user picks 'B', selection=‘B’, output is: 6-37
I = V/R R = V/I Wrong selection.
Program 6.6b (with ‘break’)
switch (selection)
{case 'A': printf("V = I*R");
break;
//selection=‘B’ does not match ‘A’ so printf()and
break are not executed
case 'B': printf("I = V/R");
break;
//selection=‘B’ matches ‘B’ so I = V/R is printed.
Since is break present, the remaining statements
below are ignored
case 'C': printf("R = V/I");
break;
default: printf("Wrong selection. ");
}
If user again picks 'B', selection=‘B’, output is: 6-38
I = V/R
The Conditional Operator (?:)

This is a ternary operator acting on 3 operands. It


is related to if-else.

expr1 ? expr2 : expr3


which is equivalent to
If expr1 is true,
if (expr1) expr2 return expr2.
else expr3 Else, return expr3

status = (mark >= 50) ? 'P' : 'F';

expr1 expr2 expr3


If mark ≥ 50, return ‘P’ to status. Else, 6-39
return ‘F’ to status.
Summary
1. Relational operators (> >= < <= == !=)

2. Logical operators (&& || !)

3. if, if-else, nested if

4. switch-case and break

5. conditional operator (?:)

6-40

You might also like