CSE-141: Structured Programming
Lecture 07-09: Decision Making
Instructor
Md. Sabir Hossain
Lecturer
Dept. of CSE, CUET
Mobile: 01737143868/01882826575
Email:
[email protected]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?”
• A flowchart is a diagram that depicts Read Hours
the “flow” of a program.
Display message “How
much do you get paid per
• The figure shown here is a flowchart hour?”
for pay-calculating program.
Read Pay Rate
Multiply Hours by Pay
Rate. Store result in
Gross Pay.
Display Gross Pay
END
10
Rounded
Basic Flowchart Symbols START Rectangle
Display message
“How many
hours did you
work?”
• Notice there are three types Read Hours
of symbols in this Display message
flowchart: “How much do
you get paid per Parallelogram
hour?”
– rounded rectangles
– parallelograms Read Pay Rate
– 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?”
• Terminals Read Hours
– represented by rounded Display message
rectangles “How much do
you get paid per
hour?”
– indicate a starting or
ending point Read Pay Rate
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?”
• Input/output Operations Read Hours
– represented by parallelograms
Display message
– indicate an input or output “How much do Input/Output
operation you get paid per
hour?” Operation
Read Pay Rate
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?”
• Processes Read Hours
– 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
Flowchart Display message Operation
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?”
Read Pay Rate
Multiply Hours
by Pay Rate.
Store result in
Variable Contents: Gross Pay.
Hours: ? Display Gross
Pay Rate: ? Pay
Gross Pay: ? END
15
START
Stepping Through the
Flowchart Display message
“How many
hours did you
work?”
How many Input Read Hours
hours did Operation
you work? (User types Display message
40
40) “How much do
you get paid per
hour?”
Read Pay Rate
Multiply Hours
by Pay Rate.
Store result in
Variable Contents: Gross Pay.
Hours: 40 Display Gross
Pay Rate: ? Pay
Gross Pay: ? END
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?”
Read Pay Rate
Multiply Hours
by Pay Rate.
Store result in
Variable Contents: Gross Pay.
Hours: 40
Display Gross
Pay Rate: ? Pay
Gross Pay: ? END
17
Stepping Through
Stepping Through the
START
Flowchart Display message
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?”
Input Read Pay Rate
Operation
(User types Multiply Hours
20) by Pay Rate.
Store result in
Variable Contents: Gross Pay.
Hours: 40
Display Gross
Pay Rate: 20 Pay
Gross Pay: ? END
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?”
Read Pay Rate
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
Gross Pay: 800 END
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?”
Read Pay Rate
Multiply Hours
by Pay Rate.
Store result in
Variable Contents: Gross Pay.
Hours: 40
Output Display Gross
Pay Rate: 20 Operation Pay
Gross Pay: 800 END
20
Symbols Used in Flowchart
Symbol Name Function
Start/end An oval represents start or end point
Arrows An arrow shows the relationship between
the representative shapes
Input/Output A parallelogram represents input or
output
Process A rectangle represents a process
Decision A diamond indicates a decision
Connect A circle connect line to process
21
Four Flowchart Structures
• Sequence
• Decision
• Repetition
• Case
22
Sequence Structure
• A series of actions are performed in sequence
• The pay-calculating example was a sequence flowchart.
23
Decision Structure
• A new symbol, the diamond, indicates a yes/no question. If the
answer to the question is yes, the flow follows one path. If the
answer is no, the flow follows another path
NO YES
24
Decision Structure
• The flowchart segment below shows how a decision structure
is expressed in C++ as an if/else statement.
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
• The flowchart segment below shows a decision structure with
only one action to perform. It is expressed as an if statement in
C++ code.
Flowchart
C Code
NO YES
if (x < y)
x < y?
a = x * 2;
Calculate a
as x times 2.
26
Repetition Structure
• A repetition structure represents part of the program that
repeats. This type of structure is commonly known as a loop.
27
Repetition Structure
• The flowchart segment below shows a repetition structure
expressed in C++ as a while loop.
Flowchart C++ Code
while (x < y)
YES x++;
x < y? Add 1 to x
28
Controlling a Repetition Structure
• The action performed by a repetition structure must eventually
cause the loop to terminate. Otherwise, an infinite loop is
created.
• In this flowchart segment, x is never changed. Once the loop
starts, it will never end.
• QUESTION: How can this
flowchart be modified so
it is no longer an infinite
YES
loop? x < y? Display x
29
Controlling a Repetition Structure
• ANSWER: By adding an action within the repetition that
changes the value of x.
YES
x < y? Display x Add 1 to x
30
A Post-Test Repetition Structure
• The flowchart segment below shows a post-test repetition
structure expressed in C++ as a do-while loop.
Flowchart
Display x
C++ Code
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
bonus = 100 bonus = 200 bonus = 400 bonus = 800
33
The biggest of three inputted numbers
Flowchart START
Read A, B, C
Yes Yes No Yes
A>C? A>B? B>C?
No No
Print A Print C Print B
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
Returns true if both conditions are
true
|| (logical OR)
Returns true if either of its conditions is true
! (logical NOT, logical negation)
Is a unary operator, only takes one operand following
Reverses the truth/falsity of its condition
Returns true when its condition is false
41
Logical Operators Truth Table
P Q P && Q P || Q !P
true true true true false
true false false true false
false true false true true
false false false false true
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
false true block
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
false block true block
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
Once a condition is met, the rest of the statements are skipped
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,
will be executed independent of the value of grade.
• The statement,
will execute only if grade is
greater than or equal to
55
90.
The dangling else
Note: the compiler matches an else with the closest unmatched if
The above will be treated as
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
case b case b action(s) break
case z case z action(s) break
default action(s)
63
The switch Multiple-Selection
Structure
Without Breaks
case a case a action(s)
case b case b action(s)
case z case z 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
Md. Sabir Hossain, CSE, CUET