L07-09 - Decision Making
L07-09 - Decision Making
Acknowledgment: Most of the content of this slide is adopted from Lecture notes : courtesy of Ohio Supercomputing Center, science and
technolgy support
Recap
Lecture 01: Administration & Overview of
the course
Lecture 02: Programming Paradigm
Lecture 03: Programming Languages
Lecture 04: Tokens in C, Data Types and
Variables
Lecture 05: Operators in C
Lecture 06: Standard I/O functions
2
Today’s Target-Decision Making
..
g
, Just
in
m
Freelancer
m
ra
g
g
n
o
Pr
h i
+
o No t
G PA
C
D
Only CGPA
Only Programming
3
Pre-Requisite
• Algorithms
• Rules to Write Pseudo code
• Example
• Flow-Chart
• Rules to Draw a flow-chart
• Example
4
Algorithms: Formal Definition
• Definition: An algorithm is a sequence of
unambiguous instructions for solving a problem.
• Properties of an algorithm
– Finite: the algorithm must eventually terminate
– Complete: Always give a solution when one exists
– Correct (sound): Always give a correct solution
• There can be many algorithms to solve the same
problem
5
Good Pseudo-Code: Example
Intersection
Input: Two finite sets A, B
Output: A finite set C such that C = A B
1. C0
2. If |A|>|B|
3. Then Swap(A,B)
4. End
5. For every x A Do
6. If x B
7. Then C C {x} Union(C,{x})
8. End
9. End
10. Return C
6
Algorithms: Pseudo-Code
• Algorithms are usually presented using pseudo-code
• Bad pseudo-code
– gives too many details or
– is too implementation specific (i.e., actual C++ or Java code or giving
every step of a sub-process such as set union)
• Good pseudo-code
– Is a balance between clarity and detail
– Abstracts the algorithm
– Makes good use of mathematical notation
– Is easy to read and
– Facilitates implementation (reproducible, does not hide away
important information)
7
Writing Pseudo-Code: Advice
• Input/output must properly defined
• All your variables must be properly initialized, introduced
• Variables are initiated, assigned using
• All `commands' (while, if, repeat, begin, end) bold face
\bf
For i 1 to n Do
• All functions in small caps Union(s,t) \sc
• All constants in courier: pi 3.14 \tt
• All variables in italic: temperature 78 (\it, \em)
8
Designing an Algorithm
• A general approach to designing algorithms is as follows
– Understanding the problem, assess its difficulty
– Choose an approach (e.g., exact/approximate, deterministic/
probabilistic)
– Choose appropriate data structures (e.g. Array, String, Structure,
Union)
– Choose a strategy
– Prove
1. Termination
2. Completeness
3. Correctness/soundness
– Evaluate complexity (Running Time and Space Requirement)
– Implement and test it
– Compare to other known approach and algorithms
9
START
What is a Flowchart?
Display message “How
many hours did you
work?”
END
10
Rounded
Basic Flowchart Symbols START Rectangle
Display message
“How many
hours did you
work?”
– a rectangle
Multiply Hours
• Each symbol represents a Rectangle
by Pay Rate.
Store result in
different type of operation. Gross Pay.
Display Gross
Rounded Pay
Rectangle
END
11
Basic Flowchart Symbols START Terminal
Display message
“How many
hours did you
work?”
Multiply Hours
by Pay Rate.
START Store result in
Gross Pay.
Display Gross
Pay
END Terminal
END
12
Basic
Basic Flowchart Symbols
Flowchart Symbols START
Display message
“How many
hours did you
work?”
– represented by parallelograms
Display message
– indicate an input or output “How much do Input/Output
operation you get paid per
hour?” Operation
Multiply Hours
by Pay Rate.
Display message Store result in
Gross Pay.
“How many
Read Hours
hours did you Display Gross
Pay
work?”
END
13
Basic Flowchart Symbols START
Display message
“How many
hours did you
work?”
– represented by rectangles
Display message
– indicates a process such as a “How much do
mathematical computation or you get paid per
hour?”
variable assignment
Read Pay Rate
Multiply Hours
by Pay Rate.
Process Store result in
Multiply Hours Gross Pay.
by Pay Rate.
Store result in Display Gross
Pay
Gross Pay.
END
14
Stepping Through
Stepping Through the
START
Output
the Flowchart
“How many
hours did you
work?”
Read Hours
How many
hours did
you work?
Display message
“How much do
you get paid per
hour?”
Multiply Hours
by Pay Rate.
Store result in
Variable Contents: Gross Pay.
15
START
Stepping Through the
Flowchart Display message
“How many
hours did you
work?”
Multiply Hours
by Pay Rate.
Store result in
Variable Contents: Gross Pay.
16
START
Stepping Through the
Flowchart Display message
“How many
hours did you
work?”
Read Hours
How much
do you get
paid per
Display message
hour?
“How much do
Output you get paid per
Operation hour?”
Multiply Hours
by Pay Rate.
Store result in
Variable Contents: Gross Pay.
Hours: 40
Display Gross
Pay Rate: ? Pay
17
Stepping Through
Stepping Through the
START
the Flowchart
“How many
hours did you
work?”
Read Hours
How much
do you get
paid per
Display message
hour? 20
“How much do
you get paid per
hour?”
Hours: 40
Display Gross
Pay Rate: 20 Pay
18
START
Stepping Through the
Flowchart Display message
“How many
hours did you
work?”
Read Hours
How much
do you get
paid per
Display message
hour?
“How much do
you get paid per
hour?”
Multiply Hours
Process: The by Pay Rate.
Store result in
Variable Contents: product of 40
times 20 is
Gross Pay.
Hours: 40 stored in
Gross Pay Display Gross
Pay Rate: 20 Pay
19
START
Stepping Through the
Flowchart Display message
“How many
hours did you
work?”
Read Hours
Your gross
pay is 800
Display message
“How much do
you get paid per
hour?”
Multiply Hours
by Pay Rate.
Store result in
Variable Contents: Gross Pay.
Hours: 40
Output Display Gross
Pay Rate: 20 Operation Pay
20
Symbols Used in Flowchart
Symbol Name Function
Start/end An oval represents start or end point
21
Four Flowchart Structures
• Sequence
• Decision
• Repetition
• Case
22
Sequence Structure
23
Decision Structure
NO YES
24
Decision Structure
Flowchart
C Code
NO YES
if (x < y)
x < y?
a = x * 2;
else
Calculate a Calculate a
as x plus y. as x times 2. a = x + y;
25
Decision Structure
Calculate a
as x times 2.
26
Repetition Structure
27
Repetition Structure
while (x < y)
YES x++;
x < y? Add 1 to x
28
Controlling a Repetition Structure
29
Controlling a Repetition Structure
YES
x < y? Display x Add 1 to x
30
A Post-Test Repetition Structure
Add 1 to x do
{
cout << x << endl;
YES x++;
x < y? } while (x < y);
31
Post-Test vs Pre-Test Repetition Structure
32
Case Structure
If years_employed = 2, If years_employed = 3,
bonus is set to 200 bonus is set to 400
If years_employed = 1, If years_employed is
CASE
bonus is set to 100 years_employed any other value, bonus
is set to 800
1 2 3 Other
33
The biggest of three inputted numbers
Flowchart START
Read A, B, C
No No
END 34
The biggest of three inputted numbers
Algorithm
Step 1: Input A, B, C
Step 2: if (A>B) then
if (A>C) then
MAX A [A>B, A>C]
else
MAX C [C>A>B]
endif
else
if (B>C) then
MAX B [B>A, B>C]
else
MAX C [C>B>A]
endif
endif
Step 3: Print “The largest number is”, MAX
35
The biggest of three inputted numbers
#include <stdio.h>
Source Code int main( )
{
float A,B,C,MAX;
scanf("%f%f%f",&A,&B,&C);
if(A>B)
{
if(A>C)
MAX=A;
else
MAX=B; }
else
{
if(B>C)
MAX=B;
else
MAX=C; }
printf("Biggest Number=%f",MAX);
return 0;
}
36
Flow of Control
Flow of control
The order in which statements are executed
Transfer of control
When the next statement executed
is not the next one in sequence
37
Flow of Control
Control structures
combination of individual statements into a logical unit
that regulates the flow of execution in a program or
function
Sequence
Selection (Making Decisions)
Repetition (Looping)
38
Boolean Expressions
Evaluate to true or false
Forms
Relational expression: <expr> <relational operator> <expr>
Examples:
7 < 5
a + b > 6
Logical expression: <Boolean expr> <logical operator> <Boolean expr>
Examples:
(x < 7) && (y > 3)
39
Relational Operators
Standard Algebraic C Relational C Condition
Relational Operator Operator Example Meaning of C Condition
Inequality
< < x<y x is less than y
<= x <= y x is less than or equal to y
> > x>y x is greater than y
>= x >= y x is greater than or equal to y
Equality
= == x == y x is equal to y
!= x != y x is not equal to y
Ch 5 p. 46
40
Logical Operators (Compound Relationals)
&& (logical AND) Ch 6 p. 72
41
Logical Operators Truth Table
P Q P && Q P || Q !P
42
Precedence of Operators
1. Unary +, unary -, !, ++, --
2. Type casting
3. *, /, %
4. +,-
5. <, <=, >, >=
6. ==, !=
7. &&
8. ||
9. =
43
The if Selection
Structure
Selection structure
used when we want the computer to choose between
two alternative courses of action
44
The if Selection
Structure
if Statement
true
Boolean
Expression
45
The if Selection Structure
General form of if:
if (Boolean Expression)
{
statement1;
statement2;
...
}
46
The if-else Selection
Structure
if
Only performs an action if the condition is true
if-else
A different action is performed when condition is
true and when condition is false
47
if-else Selection
Structure
if-else statement
false true
Boolean
Expression
48
The if-else Selection
Structure
General form of if-else:
if (expression)
{
statement1A;
statement2A;
...
}
else
{
statement1B;
statement2B;
...
49
}
The if-else Selection
Structure
Nested if-else structures
Test for multiple cases by placing if-else
selection
structures inside if-else selection structures.
50
Nested if-else
Structures
51
The if-else-if
Construct
52
The if-else-if Construct
The standard way to indent the previous code is
53
The if-else Selection
Structure
Compound statement:
Set of statements within a pair of braces
Example:
54
The if-else Selection
Structure
–Without the braces, only one statement is executed.
e.g. given the following code:
• The statement,
56
The dangling else
If the else is to match the outer if, use braces.
57
if-else
Construct
To avoid confusion, and possible errors, it is best to
use braces even for single statements.
However, code will be longer
58
Conditionals
C uses an integer to represent Boolean values
Zero is interpreted as false
Any other integer value is interpreted as true
59
Conditionals
is not a syntax error in C.
The expression, n = 0, assigns zero to n and the value of
the expression is 0. Zero is interpreted as false, and the
false branch of the if statement will be taken.
is not a syntax error in C.
The expression assigns 5 to n. 5 is interpreted as
true,
and the true branch of the if statement will be taken.
60
Conditionals
Remember to use the == operator to test for equality.
To help catch the error when the equality check
involves a constant, put the constant on the left
hand side of the ==.
For example, use
instead of
Since is not a valid assignment in C, the compiler will
detect this error when == is intended.
61
The switch Multiple-Selection
Structure
switch
Useful when variable or expression is tested for multiple
values
Consists of a series of case labels and an optional
default case
62
The switch Multiple-Selection
Structure
With Breaks
case a case a action(s) break
default action(s)
63
The switch Multiple-Selection
Structure
Without Breaks
case a case a action(s)
default action(s)
64
switch Statement
Syntax
switch (switch_expression)
{
case constant1:
statementSequence1
break;
case constant2:
statementSequence2
break;
…
case constantN:
statementSequenceN
break;
default:
defaultStmtSequenc
e
}
65
switch
Statement
The switch_expression is compared against the values
constant1, constant2, …, constantN
constant1, constant2, …, constantN must be simple
constants or constant expressions.
Can be a char or an int
66
switch Statement
Reminder
The switch statement ends
break statement
end of the switch statement
When executing the statements after a case label, it
continues to execute until it reaches a break
statement or the end of the switch.
If you omit the break statements, then after executing
the code for one case, the computer will continue to
execute the code for the next case.
67
Example of
switch
68
Allah Hafez