Você está na página 1de 72

Problem Solving with Logic

Structures

UNIT – 2
Introduction to Programming Structure

 Objectives:
 List and describe four logic structures: sequential, decision,
loops and case.
Pointers for Structuring a Program

 Use modules
 Use four logic structures:
 Sequential structure
 Decision structure
 Loop structure
 Case structure

 Eliminate the rewriting of identical processes by


using modules.
 Use techniques to improve readability, including the
four logic structures, proper naming of variables,
internal documentation, and proper indentation.
Four Logic Structures

 Logic structure control the logic of the data flow through

the module.

 The instructions and the flowcharts are combinations of

four logic structures.


 Sequential structure

 Decision structure

 Loop structure

 Case structure
Problem Solving with Sequential Logic Structure

 Objectives:

 Use of the sequential logic structure to develop a solution to a


problem

 Use the proper form for instructions in an algorithm and a


flowchart.

 Use the seven problem solving tools to develop a solution to a


problem
Sequential Logic Structure

 Simplest logical structure.

 Algorithms and flowcharts are used to represent the

problems.

 An algorithm begins with the start instruction,

executes all the instructions sequentially and ends


with the end instruction.
Flowchart for Sequential Structure

Flowchart
Algorithm
Name Age

1. Enter Name, Age


Enter
2. Print Name, Age Name, Age

3. End
Print
Name, Age

End
Solution Development

 The organizing tools are used in the six steps of


problem solving.
 Problem Analysis Chart: helps in defining and understanding
the problem, develop ideas for solution and select the best
solution.
 Interactivity chart: breaks the solution to the problem into
parts.
 IPO Chart: helps define the input, the output, and the
processing steps.
 The coupling diagram and the data dictionary : designates the
data flow between the modules. The data dictionary records
the information on the items.
 The algorithms define the steps of the solution.
 The flowcharts are a graphic form of the algorithm.
Problem Solving with Decisions

 Objectives:
 Develop problem using the decision logic structure in
conjunction with the sequential logic structure.
 Use the seven problem solving tools when developing a
solution using the decision logic structure.
 Use nested decision instructions to develop a problem
solution.
 Distinguish the different uses of straight through positive and
negative nested decision logic structures.
 Convert a positive decision logic structure to a negative
decision logic structure.
 Develop decision tables given a set of policies.

 Develop a decision logic structure from a decision table


Decision Logic Structure

 The decision logic structure uses the If/Then/Else


instruction.
 If the condition is true then execute a set of
instructions else execute another set of instructions
 Structure:
If < Condition(s) >
Then
<True Statements>
Else
<False Statements>
Flowchart for Decision Structure

If
<Condition(s)>

Instruction set Instruction set


for False for True

B
Simple Decision Statement

Algorithm Flowchart
A

If Hours > 40 then


Pay = Rate * T
F If Hours
(40+1.5*(Hours-40)) > 40

Else Pay = Rate * Pay = Rate * ( 40


Hours + 1.5 * ( Hours –
Pay = Rate * Hours 40))

B
Multiple If/Then/Else Instructions

 There are three types of decision logic:


 Straight – through logic
 All of the decisions are processed sequentially one after the
other.
 There is no else part of the instructions

 Positive logic
 Allows the flow of processing to continue through the module
instead of succeeding decisions, once the resultant of a
decision is true.
 Negative logic
 The flow of processing continues through the module when the
resultant of a decision is false.
Multiple If/Then/Else Instructions
Algorithm

If PayType = “Hourly” then


If Hours > 40 then
Pay = Rate * (40 + 1.5 * ( Hours – 40 ))
Else
Pay = Rate * Hours
Else
Pay = Salary
Multiple If/Then/Else Instructions

Flowchart
A

F If PayType = T
Hourly

F If Hours > T
40
Pay = Salary

Pay = Rate * Hours Pay = Rate * ( 40 + 1.5 *


(Hours – 40)

B
Using Straight through Logic

 All conditions are tested

 Least efficient because all the decision must be

processed.

 Used in combinations with other two logic types and

in data validation
Using Straight through Logic

 Problem: Find the amount to charge people of varying


ages for a concert ticket. When the person is under 16,
the charge is $7, when the person is 65 or over, the
charge is $5, all others are charged $10.
 The conditions are the following:

Age Charges
Age < 16 7
Age >=16 & Age <65 10
Age > = 65 5
Using Straight through Logic

Algorithm
If Age < 16 then

Charge = 7

If Age > = 16 and Age < 65 then

Charge = 10

If Age >= 65 then

Charge = 5
Using Straight through Logic Flowchart
A

If Age T
< 16
Charge = 7
F

If Age >16 T
and Age < 65
Charge = 10
F

If Age T
>= 65
Charge = 5
F
B
Positive Logic

 The computer follow a set of instructions and

continue processing if the condition is true.

 If the condition is not true then the computer

processes another decision.

 Positive logic always uses nested If/Then/Else


instructions.
Positive Logic Flowchart
Negative Logic

 Negative logic is the hardest to comprehend because

of negative terms.

 If the decision is false the computer processes

instructions and continues processing.

 When the decision is true the computer processes the

next decision.
Negative Logic Flowchart
Logic Conversion

 To convert positive logic to negative logic or vice versa do


the following:
 Change all < to >=
 Change all <= to >
 Change all > to <=
 Change all >= to <
 Change all = to <>
 Change all <> to =
 Interchange all of the Then set of instructions with the corresponding
Else set of instructions.
Which Decision Logic

 To analyze which type of decision logic is to


be used consider following questions:
 Which type would make the solution most
readable?
 Which type would make the solution the easiest
to maintain or change?
 Which would require the fewest tests when you
don’t know anything about the data?
 Which would require the fewest tests when you
are given some data?
Logic examples

 Images\logic conversion.bmp(positive to negative


logic conversion)
 Draw positive and negative logic for following
conditions.
 bonus=10 when pay<=1000
 Bonus=50 when 1000 < pay<=2000
 Bonus=100 when pay>2000

 Images\four ways to design a set of conditions.bmp


Decision Tables

 Decision table is an excellent tool to use as a


communication vehicle with a customer or with the
person for whom you are solving the problem.
 The decision table consists of four parts:
 The conditions
 The actions
 The combinations of true and false for the conditions
 The action to be taken or the consequences for each combination of
conditions.
Decision Table

Condition
T T T T F F F F
1
List of Condition
T T F F T T F F All possible
Conditions 2 Combinations
Condition of T & F
T F T F T F T F
3

Action 1 X X
List of Consequences
Action 2 X X X X
Actions
Action 3 X X
Flowchart from Decision Table

 The four steps to develop a flowchart from the


decision table are:
 Draw all decisions in flowchart form
 Compare the true and false sides of each decision, starting with
the first one.
 Eliminate any decisions that have the same instructions on
both the true and false sides, keeping the true consequence or
action.
 Redraw the flowchart.
Decision Table Example

 Store policy for charging a purchase.


 There are three conditions:
 The purchase is less than $100.

 The last payment to the account was made in the last 30 days.

 The balance of the account is less than $1,000.

 Depending on the customer each condition could be


true or false.
 The following actions could be taken:
 Credit is okay, and the customer can charge the item.
 Refer the customer to the credit department.
 Credit is denied and the customer cannot charge the item.
Decision Table Example

Purchase
T T T T F F F F
< $100
Last
List of Payment
T T F F T T F F All possible
Conditions within 30
Combinations
days of T & F
Balance <
T F T F T F T F
$1,000

Credit ok X X

Refer to
List of Credit
X X X Consequences
Actions Departme
nt
Credit
X X X
Denied
Decision Table Example

 Starting flowchart with all the decisions.

 Compare the true and false sides of each decision,

starting with the first one.

 Eliminate the decision with the same instructions on

true and false sides.

 Draw the final flowchart.


Putting It All Together (PIAT)

 Problem: The Fantastic Floral Company sells to


wholesale and retail buyers. The wholesale buyer needs a
resale number in order to buy at no tax and to receive
discounts. The retail buyer pays 6% tax. These are the
discounts to the wholesale buyer:

Amount < $ 100 Discount 2%


Amount > = $100 and < $ 500 Discount 5 %
Amount > = $500 Discount 10%

Given an amount of purchase, how much will the


customer owe the company?
Fantastic Floral Company – Problem Analysis
Chart
Given Data Required Results

Wholesale buyers: Amount Owed


• Must have resale number
• Amount of purchase Discount
<100 2%
>=100 and < 500 5%
>= 500 10 %
Retail Buyers:
• No discount
Amount of Purchase (AP)
6 % tax
Processing Required Solution Alternatives

Retail = 1.06 * AP 1. Use positive logic for discount *


Wholesale = (1 – D ) * AP 2. Use negative logic for discount
3. Use straight-through logic for
discount
Fantastic Floral Company – Interactivity Chart

Control

Read Calc Print


Fantastic Floral Company – IPO Chart

Module
Input Processing Output
Reference
1. Amount of 1. Enter input Read 1. Amount of
purchase data Calc purchase
2. Resale number 2. Calculate Calc 2. Resale #
( If 0 then a discount Print 3. Amount owed
retail 3. Calculate
customer) amount owed
4. Print output
information
Fantastic Floral Company – Coupling Diagram

PA Control AO
PA RN AO PA

RN RN

Read Calculate Print

PA – Purchase Amount
RN – Resale Number
AO – Amount Owed
Fantastic Floral Company – Data Dictionary

Item Variable Data Module Scope Pseudonym Error


Name Type Checks
Purchase PA Numeric All Local None None
Amount
Resale RN Numeric All Local None None
Number
Amount AO Numeric Control, Local None None
Owed Calculate
, Print
Algorithm & Flowchart for Control Module
Algorithm Flowchart Annotation Test
Control
Control
1. Process Read
(*PA, *RN)
Read Enter Data Go to Read Module
2. Process Calculate
Calculates amount Go to Calculate
Calculate
3. Process Print owed Module

4. End Print Prints outputs Go to Print Module

Exit Stop

Internal Documentation External Documentation


1. Title : Calculates amount owed given 1. Same as internal documentation
amount of sale and resale # 2. Explain problem
Algorithm and Flowchart for Read Module
Algorithm Flowchart Annotation Test

Read ( * PA, * RN)


Read
1. Enter Purchase
Amount and
PA
Resale Number
Enter PA
PA = Purchase 300
2. Exit Amount
& RN
RN = resale number
RN
( 0 means retail
purchase ) 27505
Exit Return

Internal Documentation External Documentation

1. Title: Enters data from keyboard 1. Same as internal documentation


Algorithm and Flowchart for Calculate Module

 Algorithm and flowchart for Calculate module


Algorithm and Flowchart for Print Module
Algorithm Flowchart Annotation Test

Print ( PA, RN, AO) Print

1. Print PA, RN
And AO
Print PA,
2. Exit None Prints Output
RN and
AO

Exit Return

Internal Documentation External Documentation


1. Title: Prints the output data 1. Same as internal documentation
Problem Solving with Loops

 Objectives:
 Develop problems using the loop logic structure in conjunction
with the decision and sequential logic structures.
 Use of seven problem solving tools to solve a problem using
the loop logic structure.
 Use counters and accumulators in a problem solution.
 Use nested loop instructions to develop a problem solution
 Distinguish the different uses of three types of loop logic
structures.
 Use recursion in s simple problem.
The Loop logic structure

 There are three types of loop structures:


 While/WhileEnd loop
 Repeats instructions while a condition is true and stops repeating
when a condition is false.

 Repeat/Until loop
 Repeats instructions while a condition is false or until a condition
is true.

 Automatic – counter loop


 Variable is set as counter and the instructions are repeated till the
counter is greater than the ending number
Tasks to be accomplished

 Counting ( Incrementing and Decrementing)


 Adding a constant to the value of a variable
 Eg: counter = counter + 1

 For decrementing add a negative value.


 Eg: counter = counter + (-1)

 Accumulating (summing a group of numbers)


 Adding a variable to the value of another variable
 Eg: sum = sum + variable
 total_sales = total_sales + sales
While/WhileEnd

 While the condition is true, repeat all instructions


between the while and whileEnd.
 Algorithm:
While < Condition(s) >
Instruction
Instruction
…..
…..
WhileEnd
While/WhileEnd

 Flowchart:
A

While F
<Condition(s)>

Instruction

Instruction

B
Decision equivalent to While/WhileEnd
Algorithm Flowchart

A
If <Condition(s) >

then
While F
Instruction <Condition(s)>
T
Instruction T

Instruction
Go to 100

Instruction

Go To

B
PIAT (Putting It All Together)

 Problem: Create the algorithm and the


flowchart to find the average age of all the
students in a class.
 Solution

 Calculates the average age in the class taking the age


of all the students as input.
 Algorithm and flowchart using While/WhileEnd
Repeat/Until Loop

 Repeat the set of instructions between the repeat and


until, until a condition is true.
 Two major difference with While/WhileEnd
 In While/WhileEnd the program continues the loop as long as
the condition is true whereas in Repeat/Until loop the
program stops the loop process when the resultant of the
condition is true.
 In While/WhileEnd the condition is processed at the
beginning whereas in Repeat/Until, the condition is processed
at the end.
Repeat/Until Loop

 Format of Repeat/Until algorithm is:


Repeat
Instruction
Instruction
…..
…..
Until <Condition(s)>
Repeat/Until Loop

 Flowchart A
Repeat

Instruction

Instruction

Until
F <Condition(s)>

B
Decision equivalent to Repeat/Until
PIAT (Putting It All Together)

 Problem: Create the algorithm and the


flowchart to find the average age of all the
students in a class.
 Solution

 Calculates the average age in the class taking the age


of all the students as input.
 Algorithm and flowchart using Repeat/Until loop
Automatic – Counter Loop

 A variable value is incremented or decremented each time the loop is


repeated.
 Counter variable is initialized with some starting value.
 The loop repeats until the counter is greater than an ending number.
 Algorithm:
Loop : Counter = Begin to End step s
Instruction
Instruction
…..
…..
Loop-End: Counter
Automatic – Counter Loop

A
 Flowchart
C
Begin End
Step

Instruction

Instruction

D
Decision Equivalent to Automatic Counter Loop
While/WhileEnd loop Equivalent of the
Automatic counter loop
Repeat/Until loop equivalent to Automatic
Counter Loop
Rules for Automatic Counter Loop
 For incremental loop:
 When the computer executes the loop instruction it sets the counter
equal to the beginning number.
 When the computer executes the loop end, it increments the counter.
 When the counter is less than or equal to the ending number, the
processing continues at the instruction that follow the loop
instruction. When the counter is greater than the ending number, the
processing continues at the instruction that follows the loop-end
instruction.
 For decremented loop:
 Counter is decremented instead of incremented at the end of the
loop.
 When the counter is greater than or equal to the ending value, the
loop continues, instead of when it is less than or equal to the ending
value when incrementing.
PIAT (Putting It All Together)

 Problem: Create the algorithm and the


flowchart to find the average age of all the
students in a class.
 Solution
 Calculates the average age in the class taking the age
of all the students as input.
 Algorithm and flowchart using Automatic counter
loop
Nested Loops

 Loops can be nested like decisions.

 Each loop is nested inside the loop just outside it.

 The inner loop does not have the same types of loop

structures as the outer loop.

 Example of nested loops:

 Nested loop using while/WhileEnd and Repeat/Until

 Nested loop using automatic counter and Repeat/until


Indicators

 Indicators are the variables that a programmer sets


within a program to change the processing path or to
control when the processing of a loop should end.
 Eg: flags, switches or trip values.

 An error indicator designates that an error has


occurred in the input or the output. (eg: true or false)
 An end-of-data indicator designates that there is no
more data to be entered. (eg: age = 0)
Recursion

 Recursion occurs when a module/function calls itself.

 The condition that ends the loop must be within the

module.

 Recursive procedures can be replaced by conventional

loop structures.

 Example of Recursion

 Explanation of Recursion function


Problem Solving with Case Logic Structure

 Objectives:

 Develop problems using the case logic structure in conjunction

with the loop, decision and sequential logic structure.

 Use the seven problem-solving tools when developing a

solution using the case logic structure.


The Case Logic Structure

 Case logic structure is made of several or many set of

instructions one of which will be selected by the user

and executed by the programmer.

 It does not enable the program to loop back to select

another option.
The Case Logic Structure

 Format of Case logic structure:


Case of variable
= CONSTANT 1
Actions for variable = CONSTANT 1
=CONSTANT 2
Actions for variable = CONSTANT 2
…..
…..
Otherwise:
Actions for variable = anything else
End of Case
The Case Logic Structure Flowchart
Decision Equivalent of Case Logic Structure
Codes

 Codes are some characters, character strings that a


programmer uses to name the options, the constants
in a case structure.
 The major difference between indicators and codes
are:
 Codes are data to be entered by the user. Indicators are
internal signals to change the processing path.
 A code can have a value of many different types. The value of
indicator can be logical data, true or false
PIAT (Putting It All Together)

 Problem 1: A company has four different medical


plans. The programmer has given each plan a code
corresponding to the beginning initial of the
company:
Plan 1 = F, Plan 2 = B, Plan 3 = K and Plan 4 = E.
The company pays for all of plan 1. The individual
has to pay for the part of the others. The Payroll
deduction for Plan 2 = 4.65, for Plan 3 = 7.85 and for
Plan 4 = 5.50. Any other codes are considered in
error. Write an algorithm and draw the flowchart for
a module to determine the payroll deduction.
 Solution for the Problem
PIAT (Putting It All Together)

 Problem 2: Calculate the employee’s pay. The


codes are as follows:
H = Hourly Pay = rate * hours
P = Piece work Pay = rate * number of pieces
C = Commission Pay = commission * sales
S = Salary Pay = salary
Any other code will considered as error.

 Solution for the problem

Você também pode gostar