Chapter 2 Problem Solving
Chapter 2 Problem Solving
PROBLEM SOLVING
• This chapter will cover the following topics:
– Problem Solving Concepts for the Computer
– Pre-Programming Phase
– Programming Or Implementation Phase
What Problem Can Be Solved By
Computer
• When the solution can be produced by a set of
step-by-step procedures or actions.
• This step-by-step action is called an algorithm.
• The algorithm will process some inputs and
produced output.
• Solving problem by computer undergo two
phases:
– Phase 1:
• Organizing the problem or pre-programming phase.
– Phase 2:
• Programming phase.
PRE-PROGRAMMING PHASE
• This phase requires five steps:
– Analyzing the problem.
– Developing the Hierarchy Input Process
Output (HIPO) chart or Interactivity Chart (IC).
– Developing the Input-Process-Output (IPO)
Chart.
– Drawing the Program flowcharts.
– Writing the algorithms.
PRE-PROGRAMMING PHASE
• Analyzing The Problem
– Understand and analyze the problem to
determine whether it can be solved by a
computer.
– Analyze the requirements of the problem.
– Identify the following:
• Data requirement.
• Processing requirement or procedures that will be
needed to solve the problem.
• The output.
PRE-PROGRAMMING PHASE
PAYROLL
0000
Payroll
0000
Area
0000
area = 3.14 x
radius Display area
radius x radius
1000 3000
2000
Problem 3
• Write a Hierarchy Input Process Output (HIPO) to compute and
display the temperature inside the earth in Celsius and Fahrenheit.
The relevant formulas are
Celsius = 10 x (depth) + 20
Fahrenheit = 1.8 x (Celsius) + 32
Temperature
0000
Get depth
1100
Problem 4
• Write a Hierarchy Input Process Output
(HIPO) that asks a user to enter the
distance of a trip in miles, the miles per
gallon estimate for the user’s car, and the
average cost of a gallon of gas. Calculate
and display the number of gallons of gas
needed and the estimated cost of the trip.
Estimation Cost
0000
READ PRINT
QUANTITY TOTALSALE
A STOP
PRE-PROGRAMMING PHASE
• Finding Average Problem
– Read a sequence of number, find the average of the
number and print the average.
– Solution: Stepwise Analysis of Average Problem
• Start the processing
• Read a number
• Add the number
• Repeat reading until last data
• Calculate the average
• Print the average
• Stop the processing
PRE-PROGRAMMING PHASE
START
READ
NUMBER
CALCULATE
AVERAGE
PRINT
AVERAGE
STOP
PRE-PROGRAMMING PHASE
START
X
COUNTER
=∅
AVERAGE = TOTAL
READ NUMBER COUNTER
PRINT AVERAGE
TOTAL = TOTAL + NUMBER
COUNTER = COUNTER + 1
STOP
END OF
DATA
X
B
START
AVERAGE = TOTAL
COUNTER
COUNTER
=∅
PRINT
TOTAL AVERAGE
=∅
A
STOP
READ
NUMBER
NUMBER = B
-999999
COUNTER = COUNTER + 1
A
PRE-PROGRAMMING PHASE
• Writing the Algorithm (Pseudocode)
– Pseudocode means an imitation computer code.
– It is used in place of symbols or a flowchart to
describe the logic of a program. Thus, it is a set of
instructions (descriptive form) to describe the logic of
a program.
– Pseudocode is close to the actual programming
language.
– Using the Pseudocode, the programmer can start to
write the actual code.
START
READ
PRICE Algorithm:
Start
READ
QUANTITY Read price, quantity
Sale = price x quantity
Print Sale
SALE = PRICE × End
QUANTITY
PRINT
SALE
STOP
Example: Flowchart & Algorithm
Order of Execution of Instructions : Payroll System
Structuring a Program
• Develop efficient computer solution to problems:
1. Use Modules
2. Use four logic structures
a. Sequential structure
• Executes instructions one after another in a sequence.
a. Decision structure
• Branches to execute one of two possible sets of instructions.
a. Loop structure
• Executes set of instruction many times.
a. Case structure
• Executes one set of instructions out of several sets.
1. Eliminate rewriting of identical process by using modules.
2. Use techniques to improve readability including four logic
structure, proper naming of variables, internal documentation
and proper indentation.
Sequential Logic Structure
The Decision Logic Structure
• Implements using the IF/THEN/ELSE instruction.
• Tells the computer that IF a condition is true,
THEN execute a set of instructions, or ELSE
execute another set of instructions
• ELSE part is optional, as there is not always a set
of instructions if the conditions are false.
• Algorithm:
IF <condition(s)> THEN
<TRUE instruction(s)>
ELSE
<FALSE instruction(s)
Decision Logic Structure
Examples of conditional expressions
• A < B (A and B are the same data type
– either numeric, character, or string)
• X + 5 >= Z (X and Z are numeric data)
• E < 5 or F > 10 (E and F are numeric
data)
• DATAOK (DATAOK – logical datum)
Example
• Assume your are calculating pay at an
hourly rate, and overtime pay(over 40
hours) at 1.5 times the hourly rate.
– IF the hours are greater than 40, THEN the
pay is calculated for overtime, or ELSE the
pay is calculated in the usual way.
Example Decision Structure
NESTED IF/THEN/ELSE
INSTRUCTIONS
• Multiple decisions.
• Instructions are sets of instruction in which
each level of a decision is embedded in a
level before it.
NESTED IF/THEN/ELSE INSTRUCTIONS
The Loop Logic Structure
• Repeat structure
• To solve the problem that doing the same
task over and over for different sets of data
• Types of loop:
– WHILE loop
– Do..WHILE loop
– Automatic-Counter Loop
Loop Logic Structure
WHILE loop
WHILE loop
• Do the loop body if the condition is true.
• Example: Get the sum of 1, 2, 3, …, 100.
– Algorithm:
• Set the number = 1
• Set the total = 0
• While (number <= 100)
– total = total + number
– number = number + 1
• End While
• Display total
WHILE loop
Start
Set number = 1
Set total = 0
No
number <= 100
Yes
Display total
total =
total + number
End
number =
number + 1
DO…WHILE Loop
• The body of the loop will process first
before check the condition.
• Example: Get the sum of 1, 2, 3, …100.
DO…WHILE Loop
DO…WHILE Loop
Start
Set number = 1
Set total = 0
total = No
total + number
Yes End
number <= 100
Automatic Counter Loop
• Use variable as a counter that starts
counting at a specified number and
increments the variable each time the loop
is processed.
• The beginning value, the ending value and
the increment value may be constant. They
should not be changed during the
processing of the instruction in the loop.
Automatic-Counter Loop
Automatic-Counter Loop
NESTED LOOP
NESTED LOOP
The Case Logic Structure
• Made up of several or many sets of instructions,
only one of which will be selected by the user and
executed by the computer
• Algorithm:
CASE OF VARIABLE
= constant1:
actions for VARIABLE = constant1
= constants2:
actions for VARIABLE = constant2
…
OTHERWISE:
Actions for VARIABLE = anything else
END-OF-CASE
Case Logic Structure
Case Logic Structure
• Example: 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, Plan 4
= E.
The company pays for all of Plan 1. The individual
has to pay for 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 the algorithm and draw the flowchart for
a module to determine the payroll deduction.
Example of Case Logic Structure
Programming Or Implementation
Phase
• Transcribing the logical flow of solution steps in
flowchart or algorithm to program code and run
the program code on a computer using a
programming language.
• Programming phase takes 5 stages:
• Coding.
• Compiling.
• Debugging.
• Run or Testing.
• Documentation and maintenance.
Programming Or Implementation
Phase
• Once the program is coded using one of the
programming language, it will be compiled to
ensure there is no syntax error. Syntax free
program will then be executed to produce output
and subsequently maintained and documented
for later reference.
CODING
NO SYNTAX
ERROR
EXECUTE OR
RUN
DOCUMENTATION
OR MAINTENANCE
Problem 1
Write a Problem Analysis Chart (PAC) to convert
the distance in miles to kilometers where 1.609
kilometers per mile.
start
read miles
km = 1.609 x miles
print km
end
Problem 2
• Write a Problem Analysis Chart (PAC) to find an
area of a circle where area = pi * radius * radius
start
read radius
print area
end
Problem 3
• Write a problem analysis chart (PAC) that
asks a user to enter the distance of a trip
in miles, the miles per gallon estimate for
the user’s car, and the average cost of a
gallon of gas. Calculate and display the
number of gallons of gas needed and the
estimated cost of the trip.
start A
read distance
Read cost_gallon
total_gas =
distance / mile_gallon Print total_gas,
total_cost
A end
Programming Or Implementation
Phase
• Coding
– Translation or conversion of each operation in the
flowchart or algorithm (pseudocode) into a computer-
understandable language.
– Coding should follow the format of the chosen
programming language.
– Many types or levels of computer programming
language such as:
– Machine language
– Symbolic language or assembly language
– Procedure-oriented language
– The first two languages are also called low-level
programming language. While the last one is called
high-level programming language.
Programming Or Implementation
Phase
• Machine Language
– Machine language uses number to represent letters,
alphabets or special character that are used to
represent bit pattern.
– Example:
• an instruction to add regular pay to overtime pay, yielding
total pay might be written in machine language as follows:
16 128 64 8
• in which 16 is a code that mean ADD to the computer. The
128 and 64 are addresses or location at which regular pay
and overtime pay are stored. The 8 represents the storage
location for the total pay.
Programming Or Implementation
Phase
• Sometimes, bit pattern that represent
letters and alphabets are used for coding.
– Example:
Instead of: 16 128 64 8
Use: 10000 10000000 1000000 1000
Module 1 Module 2
Coupling
allows
modules to
share data Module 3 Module 4
The Modules and The Functions
• The programmer breaks the problem into
modules, each with specific function.
• It is much easier to write and test many
small modules than a single large program.
• Modules are arranged according to
processing order in interactivity chart.
The rules for designing modules
1. Each module is an entity and has one entrance
and one exit.
2. Each module has a single function such as
printing, calculating or entering data.
3. Each module is short enough to be easily read
and modified.
4. The length of module governed by its function
and the number of instruction to be executed.
5. A module is developed to control the order of
processing.
Types of modules
1. Control module
• Show the overall flow of data through the program.
All other modules are subordinate to it.
1. Init module
• Also called the preparation module, process
instruction that are executed only once – at the
beginning.
1. Process Data module
• May be processed only once, or may be part of a
loop.
1. Calculation Modules
• Do arithmetic calculations.
Types of modules
2. Print Modules
• Print output lines.
2. Read and Data validation modules
• Read or input data, validate data
• Validation modules separate from read modules
4. Wrap-up module
• Execute only once at the end.
• Include closing file and printing totals.
4. Event module
• Such as mouse down, mouse up, key entry.
Local and Global Variables
• The concept of local and global variables to
allow cohesion and coupling to occur.
• Local variables
– defined within a module
– used only by the module itself
• Global variables
– defined outside of the individual modules
– can be used by all modules
Scope of Local and Global Variables