You are on page 1of 25

Introduction to Programming for Business

Problem Solving and Algorithms

Learning Objectives
• To understand what it means to be a “problem solver” and a “creative thinker”.

• To understand and to be able to follow the steps for solving a problem.

• To be able to determine a set of steps to derive a solution to a simple problem.

• To understand what an algorithm is and what rules apply when developing one.

• To understand the few basic operations that a computer can perform.

• To understand the importance of testing an algorithm and how to test it.

• To understand the introductory concepts of programming.

• To be able to write pseudocode and draw IPO diagrams to solve simple problems.

• To understand what a computer program is and how it relates to pseudocode.

1.1 Introduction
Problems are a part of life. You have already faced many problems in your life and you
undoubtedly face some right now. You will become more effective, and therefore, happier, if you
become a better problem solver.

Not having any problems would essentially leave you with no choices in life, which would be dull
and uninteresting. In fact, life consists of a constant stream of problems, some of which are not
really undesirable. Sometimes we even create problems for the enjoyment of the challenge of
solving them. Athletic contests, puzzles and many games present problems that have been created
for the purpose of trying to overcome obstacles and "win".

Becoming an effective problem solver does not merely involve applying a problem solving method
in a mechanical fashion any more than becoming a mature critical thinker involves mastering a set
of thinking skills. Rather, solving problems, like thinking critically, reflects a total approach to
making sense of experience. When we think like problem solvers, we approach the world in a
distinctive way. Instead of avoiding difficult problems, we have the courage to meet them head-on
and the determination to work through them. Instead of acting impulsively or relying exclusively
on the advice of others, we are able to make sense of complex problems in an organized way and
develop practical solutions and initiatives.

By Thayne Breetzke Copyright © Thayne Breetzke (University of Fort Hare) 1


Introduction to Programming for Business

1.2 Creative Thinking


To be creative is to be imaginative and original in developing new works of art, products, services,
uses of materials or ways of doing things. Creative thinking is not a new way to problem solving.
An example from ancient times involves Hammurabi, king of ancient Babylon, who was concerned
about getting people to a water supply. He solved the problem by realizing that it would be more
practical to find a way of getting the water to his people. Through this type of thinking and
problem solving, the concept of a canal was developed.

Everyone can do creative thinking and problem solving. We can all learn to use the abilities of our
right brain more fully. We can learn to perceive characteristics and relationships that otherwise
would go unnoticed by others. Creative thinking is not just a magic bursting of ideas in the minds
of especially gifted individuals. Even though some people have more natural creative talent than
others, we can all be creative in some ways.

To be creative is to be original. The objectives of creative people are usually to express


themselves, to make life more interesting and to seek improvements in their surroundings. The
world is constantly presenting its inhabitants with new problems and human beings are also
constantly seeking new or better solutions to old problems. Some of the best future solutions will
be the result of creative thinking.

Although creative thinking is not as structured as traditional problem solving, creative people have
demonstrated that they have several characteristics in common. If we want to become more
creative, it may help to try and develop the characteristics shown in the figure below:

Questioning
attitude

Ability to
Flexibility
concentrate

Characteristics
of a creative
thinker

Self-
Persistence
confidence

Characteristics of creative thinkers

By Thayne Breetzke Copyright © Thayne Breetzke (University of Fort Hare) 2


Introduction to Programming for Business

1.2.1 Brainstorming
Creative thinking can also be done by a group. One type of group creative thinking has been made
popular by Alex Osborn and is called brainstorming. When brainstorming:

1. Criticism is not allowed. This will come later when the ideas are evaluated.

2. The wilder the idea, the better. It is easier to discard or modify ideas than to think of new
ones.

3. Quantity is more important than quality - the more ideas, the better.

4. Combinations and variation of ideas are welcome. One idea leads to another.

1.2.2 Lateral and Vertical Thinking


Lateral thinking involves taking on different viewpoints and approaches to problem solving.
Sometimes we have difficulty solving a problem because we are viewing it in the same way we
have approached similar problems in the past. Lateral thinking is different from vertical thinking or
logical thinking which proceeds step-by-step in a given direction.

1.2.3 Exercises
1. Connect all of the following nine dots by using only four straight lines and without lifting
your pen from the paper or going back along the same path.

2. Move two of the following matches to make two squares:

By Thayne Breetzke Copyright © Thayne Breetzke (University of Fort Hare) 3


Introduction to Programming for Business

3. What is the next number in the following sequence:

1, 3, 4, 7, 11, 18, ??

4. You have 14 black socks, 10 red socks and 6 white socks mixed up in a drawer. What is the
smallest number of socks you need to take out of the drawer without looking to be sure of
having a matching pair (i.e. at least two of the same colour)?

5. Siya needs to send a secret message in a box to John at the other side of town.
They both have a padlock, but for security reasons, they only have keys for
their own padlocks. How can Siya send the message to John in such a way
that John can open the box, but nobody else can intercept the box and read the
message?

6. Three travellers register at a hotel and are told that their rooms will cost R100 each so they
pay R300. Later the clerk realizes that he made a mistake and should have only charged
them R250. He gives a bellboy R50 to return to them but the bellboy is dishonest and gives
them each only R10, keeping R20 for himself. So, the men actually spent R270 and the
bellboy kept R20. What happened to the other R10 of the original R300?

7. Professor Random can only take one of his assistants Alex and Tandi to the science
conference. To determine who will go, he proposes a game, and puts 21 sticks on the table.
Taking turns, Alex and Tandi may pick up one, two or three sticks. Whoever picks up the
final stick must stay at home and look after the laboratory.

They toss a coin to see who goes first, and Tandi is first to pick. Alex smiles, as he knows
he is going to the conference. How does Alex make sure he wins?

By Thayne Breetzke Copyright © Thayne Breetzke (University of Fort Hare) 4


Introduction to Programming for Business

8. The "Towers of Hanoi" is an ancient problem involving three pegs. On the first peg sits a
series of n concentric disks, each of which is smaller in diameter than the disk directly
below it. The second and third pegs are initially empty. The object is to transfer all the
disks to peg 3, one disk at a time, but at no time may a larger disk rest on a smaller one.

Solve this problem for three disks (shown below), listing all the steps to be followed.

1 2 3

Can you solve the problem for four disks?

9. You have a fox, a chicken and a sack of grain. You must cross a river with only one of
them at a time. If you leave the fox with the chicken, the fox will eat the chicken. If you
leave the chicken with the grain, the chicken will eat the grain. How can you get all three
across the river safely? List your steps.

10. A programmer was dispatched to a remote town to get a program up and running. As is
often the case with programming assignments, he did not know how long the job would take
him. In any event, it was necessary for him to return to his home office in one week.

Upon his arrival at the hotel where he was to stay, he discovered that his wallet had been
stolen. All that he had with him of value was a small gold chain containing seven links.
After he discussed the problem with the hotel manager, they agreed that payment of one
link of the chain per day would be exchanged for meals and lodging. The hotel manager set
one condition, though: only one link of the chain could be cut. The programmer determined
a way to stay at the hotel from one to seven days and to comply with the hotel manager's
request. How? List all your steps.

By Thayne Breetzke Copyright © Thayne Breetzke (University of Fort Hare) 5


Introduction to Programming for Business

1.3 Problem Solving


Problem solving is a central theme in computer studies. Computers are able to solve problems by
using the information they are given and carrying out a series of steps to transform the information
into the desired results. Note that several classes of problems exist. However, we are now only
concerned with problems that have solutions that can be implemented using a computer.

1.3.1 The Problem-Solving Approach


Imagine that you have a robot that you use for domestic help. You need to design a solution for it
to make a cup of coffee. In other words, you need to determine what steps the robot would have to
carry out in order to make the cup of coffee.

The following steps illustrate the process:

1. Boil water
2. Put coffee into cup
3. Pour water into cup

However, the steps are not in sufficient detail so they need to be refined. Step 1 can be refined as
follows:

1. Boil water
1.1 Fill kettle with water
1.2 Switch kettle on
1.3 Wait until kettle has boiled
1.4 Switch kettle off

The above steps can be refined even further as follows:

1.1. Fill kettle with water


1.1.1. Place kettle under tap
1.1.2. Open tap
1.1.3. Wait until kettle full
1.1.4. Close tap

Eventually after a number of refinements, the robot will be able to make a cup of coffee. The final
solution is shown below:

1. Boil water
1.1 Fill kettle with water
1.1.1. Place kettle under tap
1.1.2. Open tap
1.1.3. Wait until kettle full
1.1.4. Close tap
1.2 Switch kettle on

By Thayne Breetzke Copyright © Thayne Breetzke (University of Fort Hare) 6


Introduction to Programming for Business

1.3 Wait until kettle has boiled


1.3.1. Wait until kettle whistles
1.4 Switch kettle off

2. Put coffee in cup


2.1 Open tin of coffee
2.1.1. Take tin of coffee from shelf
2.1.2. Remove lid of coffee tin
2.2 Take one teaspoonful of coffee
2.3 Place teaspoonful of coffee in cup
2.4 Close tin of coffee
2.4.1. Place lid on coffee tin
2.4.2. Put tin of coffee back on shelf

3. Pour water into cup


3.1 Pour water from kettle into cup until cup is full

Notice that the steps are done in sequence, from first to last.

1.3.2 Exercise
Imagine that you have given someone a set of 20 cards each showing a different number. Write
down the steps you would use to explain to the person how to sort the cards into ascending order.

1.3.3 The Steps for Solving a Problem


A well-stated problem can be divided into three parts:

1. Information describing the given (initial) situation

2. Information describing the required (final) situation

3. Information concerning the necessary transformations for going from the initial situation to
the final situation.

Think of the transformations as the set of ordered steps needed to change what is given to what is
required. Consider a recipe in a cookery book. We initially have a number of ingredients and wish
to transform them into a pizza. The recipe is an example of a problem solution divided into simpler
parts or steps describing how to transform the ingredients into the pizza.

The three parts of a problem can be summarized using a simple diagram as shown below:

Given Transformations Required


Initial situation Action/process Final situation
Three parts of a problem

By Thayne Breetzke Copyright © Thayne Breetzke (University of Fort Hare) 7


Introduction to Programming for Business

For the problem of making the pizza we can use the following diagram:

Given Transformations Required


Ingredients 1. Turn on oven Pizza
2. Mix base ingredients in bowl
3. Shape base
4. Place pizza topping onto base
5. Place pizza in oven for 30 minutes
Making a pizza

The steps in solving a problem can be summarized as follows:

1. Draw three columns entitled Given, Transformations, and Required.

2. Write in the Given column information describing the initial situation.

3. Write in the Required column information describing the final situation.

4. Write in the Transformations column the set of ordered steps that describe exactly and
unambiguously the transformation of what is given into what is required.

5. Examine each step in the Transformations column to determine whether it should be


expanded into additional steps.

6. Test the process for correctness.

1.3.4 Examples
1. Express the temperature 85 degrees Fahrenheit (F) in degrees centigrade (C).

The transformations can be shown in algebraic notation as follows:

Given Transformations Required

85°F Compute °C by evaluating °C

5 (°F - 32)
9
Transformations in algebraic notation

By Thayne Breetzke Copyright © Thayne Breetzke (University of Fort Hare) 8


Introduction to Programming for Business

The transformations can also be shown using well-known operations of arithmetic.

Given Transformations Required

85°F 1. Subtract 32 from °F °C


2. Multiply result by 5
3. Divide result from step 2 by 9
4. Stop
Transformations in arithmetic operations

2. Imagine a stack of cards with a number written on each. The problem is to find the largest
of these numbers. The solution is easy if there are only five cards because one can tell at a
glance which number of largest. However, if there are 1000 cards a quick solution is not
possible. A systematic process that works for any number of cards is needed. One such
process is shown below:

Given Transformations Required


Stack of cards with a 1. Copy number from top card onto paper. Largest number on
number on each paper.
card. 2. Remove top card from stack.

3. If stack is empty, then stop.

4. Otherwise, compare number on top card with


number on paper.

5. If number on top card is larger, then copy


number from card onto paper.

6. Go to step 2.
Finding the largest number in a stack of cards

1.3.5 Exercises
1. Construct diagrams that describe the solutions to the following problems:

a) Cut a round pizza into 8 equal pieces.


b) Put on your shoes and socks.
c) Set your alarm clock for 7 o’clock am.
d) Get petrol at a petrol station.

2. Construct a diagram that describes the solution to the following problem: Mr Math E.
Mattox has just purchased a plot in the city. The plot is square, each side measures 300m
and the entire plot is bordered by streets. His problem is to divide the plot into rectangular
sections, each with 100m frontage.

By Thayne Breetzke Copyright © Thayne Breetzke (University of Fort Hare) 9


Introduction to Programming for Business

1.4 Problem Solving with a Computer


The set of detailed, unambiguous and ordered instructions developed to describe the
transformations necessary to go from the initial situation to the final situation is known as an
algorithm. An algorithm has the following properties:

1. It must be sufficiently detailed to describe the transformations necessary to solve the


problem.

2. It must be unambiguous so that anyone can perform the transformations correctly every
time.

3. It must always give the same results for the same initial situation.

4. It must give correct results in all cases.

The following rules apply when developing an algorithm:

1. The problem must be carefully examined and understood.

2. Several solutions may be identified - the simplest one must be chosen.

3. The basic steps to solve the problem must be determined.

4. Each step must then be refined.

5. The algorithm must be traced to identify errors.

When the solution to a problem is to be implemented on a computer the solution must be stated in
terms of the set of operations that the computer can perform. One must therefore become familiar
with the few operations that computers can perform. Five of these operations are:

1. Perform arithmetic - add, subtract, multiply, and divide two numbers.

2. Compare two pieces of information (including numbers) and, depending upon the outcome
of the comparison, select one of two alternate actions.

3. Receive and output information (e.g. numbers, characters such as letters, a graphical image,
or even information about a button on the screen being clicked by the mouse).

4. Repeat any group of operations.

5. Save any piece of information for later use.

Any algorithm to be used on a computer must be stated in terms of the five well-known computer
operations.

By Thayne Breetzke Copyright © Thayne Breetzke (University of Fort Hare) 10


Introduction to Programming for Business

1.4.1 Examples
1. Suppose we have a stack of computer cards with a number punched on each. The problem
is to find the largest number. A blank card will be placed at bottom of the stack so that the
computer can determine when the stack is empty. The solution is essentially the same as the
one examined earlier. The algorithm is shown below:

Given Transformations Required


Stack of cards with 1. Get number from first card. Largest number.
number on each
card. 2. Save that number.

3. Repeat the following steps:


a. Get new number from next card.
b. If card is blank, then
(1) Write saved number.
(2) Stop.
Otherwise
(1) Compare new number with number
saved.
(2) If new number is larger, then save
new number.

Computer algorithm for finding the largest number

2. Euclid's algorithm for finding the greatest common divisor of two numbers is stated as
follows:

Divide the smaller number into the larger. If the remainder is not zero, replace the
original two numbers with the remainder and the smaller of the two numbers, and
repeat the division. Eventually the remainder will be zero, in which case the
smaller number is the greatest common divisor.

For example, the greatest common divisor of 8 and 12 is 4; 4 is the largest number that can
be divided into both 8 and 12 with a remainder of 0. Euclid’s algorithm can be applied to 8
and 12 as follows:

1. Divide the smaller number (divisor) into the larger (dividend).


12 / 8 = 1 remainder 4

2. If the remainder is not 0 (it is 4), replace the two original numbers with the remainder
and the smaller of the two numbers. The two numbers are 4 (the remainder) and 8 (the
smaller of the two original numbers).

3. Repeat the division (divide the smaller number into the larger.)
8 / 4 = 2 remainder 0

By Thayne Breetzke Copyright © Thayne Breetzke (University of Fort Hare) 11


Introduction to Programming for Business

4. Eventually the remainder will be 0 (it is). The smaller number is then the greatest
common divisor. 4 is therefore the greatest common divisor.

The computer algorithm that uses this algorithm to find the greatest common divisor is
shown below. Note that it is assumed that the two numbers will be given in ascending
order.

Given Transformations Required


Two numbers, the 1. Read the smaller number and the larger number. Greatest common
smaller followed by divisor
the larger 2. Repeat the following operations:
a. Find the remainder of the larger divided by
the smaller.
b. If remainder is zero, then
(1) Put out smaller number (divisor).
(2) Stop.
Otherwise
(1) Save remainder.
(2) Save smaller number (divisor).

Finding the greatest common divisor by computer (Euclid’s algorithm)

1.5 Testing an Algorithm


When a solution diagram is constructed, the algorithm must be tested for correctness. This is
accomplished by a hand simulation called a trace. This involves tracing through the algorithm with
some trial information to see if it produces the correct results.

The simplest way to do a trace is to make a table (called a trace table) and keep a step-by-step
record of what information is recorded. When a step or group of steps are repeated, each repetition
is called a pass. Therefore, when a group of steps are performed the first time, it is known as the
first pass. The second execution of the group is the second pass, and so on.

By Thayne Breetzke Copyright © Thayne Breetzke (University of Fort Hare) 12


Introduction to Programming for Business

1.5.1 Examples
1. A trace of Euclid's algorithm for the numbers 36 and 88 is shown below:

Smaller number Larger number Remainder


36 88
Pass 1 16
Pass 1 16 36
Pass 2 4
Pass 2 4 16
Pass 3 0
A trace of Euclid's algorithm for the numbers 36 and 88

The greatest common divisor is 4 - the smaller number.

2. A trace of the algorithm for finding the largest of the numbers 7, 5, 8, 12, 4, and 2 is shown
below.

Number Largest number


7 7
Pass 1 5
Pass 2 8 8
Pass 3 12 12
Pass 4 4
Pass 5 2
Pass 6 (blank)
A trace of the algorithm for finding the largest of the numbers 7, 5, 8, 12, 4, and 2

The largest number is 12.

By Thayne Breetzke Copyright © Thayne Breetzke (University of Fort Hare) 13


Introduction to Programming for Business

1.5.2 Exercises
1. Construct a computer solution diagram for finding the smallest number of a set of numbers,
each of which appears on one computer card.

2. Perform a trace on the algorithm in exercise 1 for the numbers 7, 5, 8, 12, 4, and 2.

3. Construct a computer solution diagram for an algorithm that finds both the smallest and
largest numbers of a set of numbers, each of which appears on a computer card.

4. Perform a trace on the algorithm in exercise 3 for the numbers 7, 5, 8, 12, 4, and 2.

5. Perform a trace on Euclid's algorithm (computer solution) for the numbers 45 and 235.

6. Perform a trace on Euclid's algorithm (computer solution) for the numbers 416 and 822.

7. Construct a computer solution diagram for printing a list of all odd numbers contained in a
set of numbers, each of which appears on a computer card.

8. Perform a trace on the algorithm in exercise 7 for the numbers 12, 7, 8, 2, 9, and 1.

9. Suppose that Mr. Rich deposits R10,000 into a savings account that earns 5% interest
annually and that Mr. Thrift deposits R5,000 into a savings account that earns 15% interest
annually. Construct a computer solution diagram that finds and prints the annual balances
until Mr. Thrift's balance exceeds Mr. Rich's. Assume no other deposits are made.

10. Construct a computer solution diagram for the following problem: Given a list of names and
ages, prepare a list of names of people aged 65 and over.

11. Construct a computer solution diagram for the following problem: Given a list of names
with ages and cities of residence, prepare a list of names of people aged 65 and over who
live in East London.

1.6 Writing Pseudocode


When solving a problem, we develop a set of systematic and ordered transformations for
transforming the initial situation into the required situation. To use the computer to perform
transformations, we must state the transformations in well-known computer operations. This can
be achieved using pseudocode. Pseudocode is English, structured and abbreviated to allow well-
known computer operations to be stated clearly and concisely.

Remember that computers are able to perform a number of operations. Five of these are:

• Perform arithmetic - add, subtract, multiply, and divide two numbers.

• Compare two pieces of information (including numbers) and, depending upon the outcome
of the comparison, select one of two alternate actions.

By Thayne Breetzke Copyright © Thayne Breetzke (University of Fort Hare) 14


Introduction to Programming for Business

• Receive and output information.

• Repeat any group of operations.

• Save any piece of information for later use.

This section takes a closer look at the pseudocode applicable to each of the operations. However, it
is necessary to first examine how a computer stores information.

1.6.1 Naming Storage Places


A computer saves, or stores, temporary information in a place called memory consisting of many
individual units, called a storage location or memory location, each uniquely identified by an
address. Each location can contain only one item of information at a time.

When writing pseudocode we use unique names to identify storage locations, instead of using
addresses. Each name corresponds with an address and describes the information stored at that
address.

For example, a storage location that is used to store an employee's hourly wage might be called
WAGE. The amount of a sale could be called AMOUNT or SALE AMOUNT. A student
identification number might be STUDENT ID or STUDID. It is important that the names be short,
natural, clear, descriptive and unambiguous. From this point on a reference to a name such as
AMOUNT will imply a reference to the information at the address identified by the name.

1.6.2 Saving Information for Later Use


Information can be placed in a storage location with an assignment statement. Keywords such as
set, assign, initialize, save, store, compute, and calculate indicate assignment in pseudocode. The
following are examples:

Assign employee number to EMPNUM.


Save the employee number in EMPNUM.

Both of the above take the employee number and place it in the memory location named
EMPNUM.

Set COUNTER to zero.


Initialize COUNTER to zero.
Store zero in COUNTER.

Each of the above stores zero in the memory location named COUNTER.

By Thayne Breetzke Copyright © Thayne Breetzke (University of Fort Hare) 15


Introduction to Programming for Business

Set X to Y.

The statement above saves the contents of the storage location named Y into the storage location
named X.

Compute AREA to be LENGTH x HEIGHT.

The statement above stores the result of LENGTH x HEIGHT in the memory location AREA.

SUM = A + B

This statement uses algebraic notation to instruct the computer to add what is stored at A to what is
stored at B and to save the sum in the storage location named SUM. Notice that the equal sign does
not mean equality, but means “store” or “save”.

COUNTER = COUNTER + 1

This statement instructs the computer to take what is in the storage location named COUNTER,
add 1 to it, and store the result in COUNTER.

1.6.3 Receiving and Outputting Information


When we enter information into a computer we use an input device (e.g. a keyboard or
microphone). The process of entering the information is called input. Computers are able to
provide information to us through output devices (e.g. a monitor or printer) and this process is
called output. We therefore use the terms input for receiving information and output for putting it
out (or outputting it). Input and output together are referred to as I/O.

Input in pseudocode is usually indicated by the keywords read and get. Output in pseudocode is
usually indicated by the keywords print, write, and put. The following are examples:

Read two numbers, SMALLER and LARGER.

This instructs the computer to use an input device to receive two numbers. The first is to be stored
in memory location SMALLER and the second in memory location LARGER.

Print SMALLER.

This instructs the computer to take the number stored in the location named SMALLER and, using
an output device, move it "outside" in some readable form.

Often one needs to print a series of characters to label output. Such a series of characters is called a
label, a character string or a literal and is enclosed in quotes. Anything placed between the
quotation marks will be printed as it appears. The following is an example:

By Thayne Breetzke Copyright © Thayne Breetzke (University of Fort Hare) 16


Introduction to Programming for Business

Print "Name"

This simply prints the word Name.

Print "X"

This prints an X character.

Print X

This prints the information in the memory location named X, for example the number 5.

Print "X = ", X

This prints X = 5, assuming that the memory location named X contains the number 5.

1.6.4 Performing Arithmetic


Computers are able to perform four basic arithmetic operations: addition, subtraction,
multiplication, and division. In pseudocode we can use the name of the operation (add, subtract,
multiply, or divide) or the algebraic symbol (+ for addition, - for subtraction, * for multiplication,
and / for division). Examine the following examples:

Add 1 to COUNTER.

This adds 1 to the number stored in the memory location named COUNTER.

SALES TAX = PRICE * TAX RATE

This multiplies PRICE with TAX RATE and stores the result in SALES TAX.

1.6.5 Comparing Information


Computers are able to compare two pieces of information and select one of two alternative actions,
depending on the outcome of the comparison. The keywords if, then and else are used. Examples
are shown below:

If NUMBER > LARGEST then


LARGEST = NUMBER
End if

This compares NUMBER with LARGEST and if NUMBER is larger, NUMBER is assigned to
LARGEST.

By Thayne Breetzke Copyright © Thayne Breetzke (University of Fort Hare) 17


Introduction to Programming for Business

If SEX = "M" then


Print "Male"
else
Print "Female"
End if

This compares SEX with the literal M and if SEX contains an M then the literal Male is printed
otherwise the literal Female is printed.

Note that End if is placed at the end of the If operation and the operations in the then and else
segments are indented so that each stands out clearly from the other.

1.6.6 Repeating Operations or Groups of Operations


Computers are able to carry out operations repeatedly without getting bored. The keywords loop,
repeat, do, and perform are commonly used to repeat an operation or group of operations. The
keywords end loop, end repeat, end do, and end perform respectively are placed after the last
operation in a repetition group to delineate clearly the bottom of the loop. Examine the following
examples:

COUNTER = 1
Loop while COUNTER <= 5
Print "*"
COUNTER = COUNTER + 1
End Loop

This prints 5 asterisks:

*
*
*
*
*

NUMBER = 1
Loop while NUMBER <= 100
Print NUMBER
NUMBER = NUMBER + 2
End Loop

This prints all odd numbers between 1 and 100.

By Thayne Breetzke Copyright © Thayne Breetzke (University of Fort Hare) 18


Introduction to Programming for Business

1.7 IPO Diagrams


So far we have used diagrams for showing what is given and what is required and the
transformation for going from what is given to what is required. Since given information must be
input into the computer and required information must be output, from now on we shall use the
column headings Input and Output, instead of Given and Required, respectively. We will also use
the column heading Process instead of Transformations. Pseudocode is given in the Process
column. Diagrams with columns Input, Process and Output are called IPO diagrams.

Let’s examine the problem of converting degrees Fahrenheit to degrees centigrade again. The
problem is stated as follows:

Construct a computer program that will convert any temperature expressed in degrees
Fahrenheit to degrees centigrade.

The IPO diagram looks as follows:

Input Process Output

Temperature in °F 1. Get temperature F Temperature in °C


2. C = (5 * (F - 32)) / 9
3. Print C, " deg C"
4. Stop
IPO diagram for converting temperatures

1.7.1 Examples
1. Earlier we looked at an algorithm for determining the largest number in a set of numbers.
The following is an IPO diagram for this problem:

Input Process Output


Stack of cards with 1. Read NUMBER from first card. Largest number.
number on each
card. 2. LARGEST = NUMBER.

3. Loop while card not blank


Read NUMBER from next card.
If NUMBER > LARGEST then
LARGEST = NUMBER.
End if
End loop.

4. Print "The largest number is ", LARGEST.

5. Stop.
IPO diagram for finding the largest number

By Thayne Breetzke Copyright © Thayne Breetzke (University of Fort Hare) 19


Introduction to Programming for Business

2. The following is an IPO diagram finding the greatest common divisor using Euclid’s
algorithm:

Input Process Output


Two numbers, 1. Read two numbers, SMALLER and LARGER. Greatest common
SMALLER divisor
followed by 2. Print "The numbers are ", SMALLER, " and ",
LARGER LARGER.

3. REMAINDER = remainder of LARGER /


SMALLER.

4. Loop while REMAINDER is not zero.


LARGER = SMALLER.
SMALLER = REMAINDER
REMAINDER = remainder of LARGER /
SMALLER.
End loop.

5. Print "Greatest common divisor is ", SMALLER.

6. Stop.
IPO diagram for finding the greatest common divisor (Euclid’s algorithm)

3. Construct an IPO diagram for the problem of finding all of the even numbers in a set of 10
numbers.

Input Process Output


Set of 10 numbers 1. COUNTER = 1 All even numbers in
2. Loop while COUNTER <= 10 set
Read NUMBER
If remainder of NUMBER / 2 = 0 then
Print NUMBER
End if
COUNTER = COUNTER + 1
End Loop
3. Stop
IPO diagram for finding all of the even numbers in a set of 10 numbers

By Thayne Breetzke Copyright © Thayne Breetzke (University of Fort Hare) 20


Introduction to Programming for Business

4. Construct an IPO diagram for the problem of finding and printing all two-digit odd numbers
that are not divisible by 3 in a set of 100 numbers.

Input Process Output


Set of 100 numbers 1. COUNTER = 1 All two digit odd
2. Loop while COUNTER <= 100 numbers not
Read NUMBER divisible by 3 in set
If NUMBER > 9 and < 100 then
If remainder of NUMBER / 2 <> 0 then
If remainder of
NUMBER / 3 <> 0 then
Print NUMBER
End if
End if
End if
COUNTER = COUNTER + 1
End Loop
3. Stop
IPO diagram for finding and printing all two-digit odd numbers that are not divisible by 3 in a set of 100 numbers

5. Construct an IPO diagram for the problem of separating lists of names of males and females
from a list containing names and sexes.

Input Process Output


List of names and 1. Loop while not past end of list 2 lists: 1 for
sexes Read NAME, SEX females and 1 for
If SEX = "F" then males.
Put NAME to female list
else
Put NAME to male list
End if
End loop
2. Stop
IPO diagram for separating lists of names of males and females from a list containing names and sexes.

1.8 Translating Pseudocode into a Computer Program


Once the pseudocode program has been developed and tested for correctness, then and only then is
it coded into a computer program using some particular computer language, for example, Visual
Basic, C# or Java. Each computer language has a set of rules, called syntax, which programmers
must adhere to.

So, a computer program can be defined as a series of instructions that are obeyed by a computer to
carry out a task, such as calculating a salary, playing a game or sending an e-mail (Bell & Parr,
2009). Programming is the process of designing/writing algorithms and coding the algorithms into

By Thayne Breetzke Copyright © Thayne Breetzke (University of Fort Hare) 21


Introduction to Programming for Business

a program using a programming language. It is the job of a programmer to write a list of


instructions to carry out a task (Bell & Parr, 2009).

Take note of the following characteristics of a program as given by Bell & Parr (2009):

• The steps are done in sequence, from the first step to the last.

• Some steps can be repeated (called repetition or iteration).

• Some steps can be carried out only if a condition is met (called selection).

• Some steps can be grouped together into a sub-task (called a method, function, procedure or
sub-routine) to simply the list of instructions.

• A step can call a sub-task/method.

• Some useful sub-tasks/methods already exist and can be called by our instructions.

• Steps can use existing objects (e.g. buttons, scroll bars and databases) to make our list of
instructions simpler.

• We can create and use our own objects.

The quality of a computer program depends on the quality of its design. Therefore, the process of
designing/writing algorithms must be done carefully. Bear the following in mind:

• The correct output depends on the input being correct as well as the program being correct.

• Algorithms must be tested to ensure that they produce the correct results. If errors are
encountered, they must be eliminated.

• Poor design and lack of developmental testing results in errors built into program as it is
developed.

• The primary goal in programming is to design and develop correct programs, not to correct
poorly designed and incorrect programs.

REMEMBER

1. If we give the computer the wrong instructions or instructions in the wrong order, the task won’t
be done correctly.

2. It is much easier to produce a correct program than it is to correct an incorrect one.

By Thayne Breetzke Copyright © Thayne Breetzke (University of Fort Hare) 22


Introduction to Programming for Business

1.9 Problem Solving and Algorithm Exercises


1. Construct an IPO diagram for the problem of accepting three numbers, adding them together
and printing the total.

2. Construct an IPO diagram for the problem of accepting a maximum temperature and a
minimum temperature and printing the average temperature.

3. Construct an IPO diagram for the problem of accepting a measurement in inches and
converting it to centimetres (cm = 2.54 * in).

4. Construct an IPO diagram for the problem of finding and printing all three-digit odd
numbers that are divisible by 3 in a set of n numbers. Do a trace through your solution with
3 appropriate numbers.

5. Construct an IPO diagram for the problem of computing the perimeter of a square with side
s. Output the values of the side and the perimeter with appropriate labels. (Assume that s is
positive).

6. Construct an IPO diagram for the problem of computing and printing a triangle’s area given
its base and height.

7. Construct an IPO diagram for computing the sum of the first n integers. For example, the
sum of the first five integers is 1 + 2 + 3 + 4 + 5 = 15. Print the value of n and the value of
the sum.

8. Perform a trace for the program in exercise 7 with n equal to 10.

9. Construct an IPO diagram for the problem of finding a student’s average test score for five
tests. Print the student’s name, five test scores and the average score, all appropriately
labelled. Perform a trace for the program for Joe Sudds, who scored 76, 85, 92, 79 and 85.

10. Construct an IPO diagram for the problem of accepting a time as a number of seconds after
midnight and outputting it as hours:minutes:seconds. For example, if the input were 50000
the output should be 13:53:20.

11. Construct an IPO diagram for the problem of accepting an input value in metres and
converting it to centimetres, millimetres and kilometres, and displaying the results.

12. Construct an IPO diagram for the problem of accepting a number from 1 to 7 and printing
the corresponding day of the week. For example, if 2 is entered then “Monday” must be
printed.

13. Construct an IPO diagram for the following problem: Input the amount of money spent to
fill a fuel tank, the price per litre, and the number of kilometres driven since last filling the
tank. Compute the kilometres used per litre, and print with headings the price per litre and
the kilometres per litre.

By Thayne Breetzke Copyright © Thayne Breetzke (University of Fort Hare) 23


Introduction to Programming for Business

14. If one wants to send a parcel, postage charged will depend on the weight of the parcel. If a
parcel weighs 2kg or less, postage will be R30.25. An additional R10.05 is levied for each
kg or part of a kg in excess of 2kg. Construct an IPO diagram for the problem of reading in
the weight of a package and printing the total amount owing. Test your solution with a trace
using a value of 3.2 as input.

15. A salesman gets a commission of 5% on sales of R1,000 or less and 10% on sales of more
than R1000. In other words, a salesman who sells goods to the value of R1,500 gets a
commission of 5% on R1,000 and a commission of 10% on R500. Construct an IPO
diagram for the problem of accepting the sales amount as input, computing the salesman’s
commission, as well as the amount the company will receive after the commission is
deducted.

16. At the beginning of a journey the reading on the odometer of a motorcar is “distance”
kilometres and the petrol tank is absolutely full. Upon completion of the journey the
reading on the odometer is “total” kilometres and it takes “number” litres to fill up the tank
again. Construct an IPO diagram for the problem of reading the values “distance”, “total”
and “number” as input and to compute the total distance travelled and the petrol
consumption,

17. Construct an IPO diagram for the problem of reading in a value for N, a positive integer,
and then determining the factorial function:

N! = 1 x 2 x ... x N

18. Construct an IPO diagram for the problem of finding the largest number from a list of five
positive integers entered by the user.

19. Construct an IPO diagram for the problem of printing a sequence of 15 numbers. The first
number is 1, the second 2, the third 4, and so on; each number is twice the preceding
number.

20. Construct an IPO diagram for the problem of accepting the name and age of a first person
and the name and age of a second person. Assume the ages are different. Print the names
and ages in the following form:

Name IS age YEARS OLD.

Determine which person is older, and print both names in the following form:

Name IS OLDER THAN name.

21. Construct an IPO diagram for the problem of accepting a customer's name, a purchase
amount, and a tax code, and computing the sales tax. Print the customer's name, purchase
amount, sales tax and total amount due. The tax codes are as follows:

0 - tax exempt (0%)


1 - state sales tax only (3%)
2 - state and local sales taxes (5%)

By Thayne Breetzke Copyright © Thayne Breetzke (University of Fort Hare) 24


Introduction to Programming for Business

1.10 References
Bell, D. & Parr, M. (2009). C# for Students. Pearson Education Limited, Great Britain.

By Thayne Breetzke Copyright © Thayne Breetzke (University of Fort Hare) 25

You might also like