Unit 8
Unit 8
Problem Solving
Program is a set of instructions, written in a specific programming language that directs the
computer to solve a problem.
Steps in Problem Solving
In order to solve a problem on the computer a series of steps must be followed in order to ensure
that the solution is accurate and logical. These steps involve:
1. Defining the problem – state what the problem is and analyze or break the problem into
significant part.
2. Proposing and evaluating the solutions – state how the problem is to be solved.
3. Determining the most efficient solution – after comparing alternative solution select the
most efficient solution.
4. Developing and representing an algorithm – this is a sequence of precise instructions for
solving a problem written in a finite amount of steps.
5. Testing and validating the solution – check the algorithm by using simple but realistic
values, in a trace table to ensure that it produces the required, valid results.
6. Implement the algorithm – a programming language is used in order to instruct the
computer to solve the problem.
IPO Charts
Input –Output-Processing (IPO) charts are used to identify the
Outputs – the goals of the problem solution.
Inputs – the information you need to solve the problem
Processes – the steps needed to convert the input information to the desired outputs.
Example
Write an IPO chart to get three numbers, find and display the sum of the numbers.
Input Processing Output
Num 1 Read three numbers Sum
The Output step – this step is used to display the result. For output we used Print.
e.g. Write a pseudocode to print the sum of numbers .
Print “Sum”
Control Structure (Statement)
The steps are identified for preparing algorithms can be written using two basic control structures
or program constructs to indicate how instructions will be carried out or how the flow of control
form one statement would take place. They are:
Selection (Conditional) – It allows for decisions to be made in a program. These steps
will be included when you have to check for any conditions to be followed or with
instructions to be carried out if a certain condition is met. The choice of options will be
dependent on whether the condition is true or false. (if- then) or (If- then-else).
Example
Print sum of three numbers if the sum is greater than 50
Start
Read Num1, Num 2, Num 3
Sum = Num 1 + Num 2+ Num 3
If total > 50 then
Print “Total”
Stop
OR
Write a pseudocode to find out if Kay is less than 13 years old. If she is output a statement
“Kay is a child” otherwise “Kay is not a child”.
Start
Read This Year
Read Birth Year
Age = this year – birth year
If age < 13 then
Print “Kay is a child”
End if
STOP
Repetition (Looping) – are useful for repeating parts of a program. That is they will repeatedly
execute a section of program until the end condition is satisfied. Once a loop is terminated,
control is returned to the first sentence after the block of sentence in the loop. The basic structure
of a loop is:
1. Initialize the variable to some start value- this variable usually determines whether or
not the loop executes or not.
2. Test the variables against a condition
3. Execute the body of the loop.
4. Update the value of the variables.
There are two types of loop statements:
Indefinite – when you do know in advance how many times to repeat the loop (While or
Repeat loop)
Definite – when you know in advance how many times to repeat the loop (For Loop)
Example
Write pseudocode read to a sequence of numbers terminated by 0 and print their sum.
Start
Sum=0
Read Numb
End while
Stop
Write a pseudocode to read 100 numbers and find their sum.
Start
Sum = 0
For counter = 1 to 100 do
Read Num
Sum = sum + num
End For
Print “Sum”
Stop
Write a pseudocode to read the name and test scores for ten students. Each student does three tests.
The pseudocode must be print the name of the student with the highest average.
Start
Havg = 0
For counter = 1 to 10 do
Read Name
Read score 1
Read score 2
Read score
Average = (score 1 + score 2 + score 3)/3
If average >Havg
Hname = average
Hname = Name
Endif
Endfor
“Print “Person with highest average is “,”Hname”
Stop
Flowcharts
Flowcharts use special geometrical objects to designate the basic steps of a program, which are:
input, processing and output. A parallelogram is used to represent the input operation, as well as
the output operation, and a rectangle is used to represent a processing/assignment statement. A
diamond is used to represent a decision (if-then-else) structure. An elliptical shape is used to
represent the terminal indicators, START or STOP. Directional arrows are used to indicate the
flow of the logic in the algorithm.
The five basic shapes are:
Design an algorithm that accepts two values, the hourly rate and the number of hours worked by
an employee. If the number of hours exceeds 40, then the excess hours should be paid at an
overtime rate of twice the hourly rate. Calculate the wages (including overtime, if any) due to the
employee.
The first step is to define the problem as follows:
The next step is to create sample data and then do a manual solution.
The first data item is $10.00 that represents the hourly rate and the second is 45 that represent the
number of hours worked. The manual solution is left as an exercise for the student.
A possible Pseudocode version of the algorithm would look like this:
Algorithm Wages
This algorithm calculates the wages (including overtime) due to an employee based on the
number of hours worked.
Read rate, hours-worked
Basic-Pay = rate * 40
Overtime = hours-worked – 40
If (overtime > 0) then
Wages = Basic-Pay + (overtime * 2* rate)
Else
Wages = rate * hours-worked
Print wages
Stop.
The flowchart version of the Wages problem would look like this
START
Basic-Pay = hours-worked * 40
Overtime = hours-worked – 40
Yes
Wages = Basic-Pay + No Wages = rate *
(overtime * 2* rate) Overtime > 0 hours-worked
Print Wages
STOP
The next problem is an example of a situation where the flowchart representation can become
quite complex. Sequential, looping and nested decision structures are used.
Problem 11
Design an algorithm that reads a list of students test scores and determines the letter grade that
corresponds to each test score, according to the following table:
The input list is terminated by a value of –1, which is used as a sentinel. Print each test score
and the corresponding letter grade.
The next step is to create sample data. Note that the problem did not state the actual number of
test scores in the list. For this problem, we do not need to know how many scores there are.
However, in another scenario, if we need to know the exact number of data items in the input
list, we have to count them as each item is read. We read the data until the end of the list is
reached. A value of –1 indicates the end of the list. The –1 is not valid data; it is merely an
indicator, to let us know that there is no more data in the input list. This value is called a sentinel.
A sentinel can be any value that does not represent valid data in the context of the problem.
We can choose any number of input values for our sample list. For example, Sample input data:
75 43 56 87 72 91 35 –1
The manual solution will be left as an exercise for the reader. The following is the solution
algorithm in Pseudocode:
Algorithm Grades
This algorithm reads test scores and determines the letter grade for each score.
Read test-score
While (test-score -1) do
If (test-score >= 80 and test-score <= 100) then{Validate the input data}
Lettergrade ‘A’
Else
If (test-score < 80 and test-score >= 70) then
Lettergrade ‘B’
Else
If (test-score < 70 and test-score >= 60) then
Lettergrade ‘C’
Else
If (test-score < 60 and test-score >= 0) then
Lettergrade D’
End-If
End-If
Print test-score, lettergrade
Read test-score
End-while
Stop
Note the indentation which highlights the structure of the logic and the flow of control of the
ifstatements and the while loop. The structure will be more evident in the flowchart version of
the algorithm.
Flowchart Version
Start
Read test-
LOOP score
Yes
test-score = -1
Print
Error
Message
No
No
Yes No Yes
test-score<= test-score test-score Lettergrade =
100
‘B’
Yes No
Lettergrade No
= ‘A’
Lettergrade = Yes Lettergrade =
test-
‘D’ score>= ‘C’
60 ?
Print Lettergrade
Stop
It can be seen that the flowchart above is quite complex and the logic is somewhat difficult to navigate.
In such circumstances, the programmer may find it easier to represent the algorithm as Pseudocode,
using appropriate indentation to show the logic and to delineate the control structures.
In problems where the flowchart cannot fit on a single page, a special symbol called a connector
is used to connect sections of the flowchart over multiple pages. The connector symbol is a small
circle with a number or letter inscribed therein, for example.
Flowchart Section
1
Flowchart Section 2
Flowchart Section 3
Truth Table
This when values are compared using Boolean operators, the results is either or false. If the value
is true it is represented with a 1, if the value is false it is represented with a 0. These tables can be
represented using AND OR and NOT operators
AND Operator - yields TRUE only if both values are TRUE
TRUE and FALSE = FALSE
TRUE and TRUE = TRUE
FALSE and TRUE = FALSE
FALSE and FALSE = FALSE
If the value A is true and the value B is true then the result of A and B is true. If any value of A
and B is false, then the result false.
A B A AND B
1 1 1
1 0 0
0 1 0
0 0 0
This is simple done by changing the zeros to one’s and the ones to zero’s.
A B NOT B
1 1 0
1 0 1
0 1 0
0 0 1
EXAMPLES
Consider A = 10, B =12, C =14, D = 11
1. A = B =False
2. A > B = False
3. (A < C) AND (B < D) = False
4. (A >B) OR (A < 5 ) = False
5. (D >A) AND (C > D) = False
6. (A > B) OR ((A + B) < (A * B) = True
7. NOT (B>D) = False
8. NOT (A >B) OR (B < D) = False
Trace Table
A trace table is a technique used to test algorithms in order to make sure that no logical errors
occur while the algorithm is being processed. The table usually takes the form of a multi-column,
multi-row table; with each column showing a variable, and each row showing each number input
into the algorithm and the subsequent values of the variables.
STEPS IN TRACING ALGORITHM
1. Choose simple input test cases which are valid. Two or Three test cases are usually
sufficient.
2. Establish what the expected result should be for each test case. that is do a manual
solution beforehand.
Read X
For M = 1 to X do
Y=X–M
Z=5*Y–M
End
Print Z
X M Y Z
4 1 3 14
4 2 2 8
4 3 1 2
4 4 0 -4
2. Second Generation Language (Assemble language) – has the same structure and
commands as machine language but allows programmers to use abbreviated words called
mnemonics, instead of binary.
High Level Language
High level languages are non machine dependent; therefore programs written on one computer
can generally be used on another similar computer. They also use key words similar to English
and are easier to write. These are:
1. Third Generation Language – are designed to be easier for you to be understood. These
languages are converted to machine code, rather like translating from one language to
another for example C, Pascal and Basic.
2. Fourth Generation Language (Natural language) - are non procedural language such
as COBOL are written to provide easy ways of designing screens and reports, and using
databases.
3. Fifth Generation Language – are sometimes regarded as very high level language, in is
a non procedural language meaning that the programmers states the goal to be achieved,
but not they steps required in order to achieve the goal.
2. Translate source code to object code (compile) – the act transferring a source code.
3. Link objects code to library routines - a program that is ready to be run by the computer
is known as executable program.
5. Maintain the program – this is the process of making any modifications to an already
developed program, to make it suitable for a particular situation.
Programming Errors
Syntax error (discovered during Compilation)
This occurs when a mistake is been made with the language rule or sentence structure of the
programming language.
Logic Error (discovered at algorithm stage)
This occurs when a programmers makes a mistake in the sequence of the sentence such as using
the wrong mathematical formula or wrong operator in an expression.
Runtime Error (discovered during execution that is after compilation)
This occurs when the program complies or runs. These errors are usually due to unexpected
events such as division by zero or a lack of memory for the computer to manipulate the data. Run
time errors can be very difficult to trace as the program may produce a result most of the time.
Programming Terms
Debugging - the process of finding the errors in the source code, understanding why they
occurred and correcting them.
Compiler – A program that translates the source program into executable machine code, and
saves the code to a file (the object program) for later execution.
Interpreter - A computer program which interactively translates and executes a source program
without permanently storing any executable code.
Assembler - A program which converts ASSEMBLY LANGUAGE into MACHINE CODE to
be used by a computer.
Source Code - Program written in high level language or assembly level language
Testing – used to ensure that our program works correctly in all situations. It is done with the
aim of finding errors in logic an syntax. There are two ways to test a program and these are
testing on paper (dry running/desk checking with the use of trace table - for logic errors) and
computer testing (compiling - for syntax errors and executing- for run time errors).
Dry Running - is the means of testing which involves the process of reading through the
program in search of errors in logic. This usually make use of trace table and test data
that is realistic but simple data (easy for the programmer to follow) from the real world.
Computer Testing - the program is compiled and executed using test data, this time on the
computer.
Documentation
Once the program is completed and is running error free it is important that you have a good
documentation. Documentation is a written guideline that helps program users to operate the
program. The following are some reasons why we need to have a good documentation.
1. It makes it easier to comprehend and use the program
2. If there is a problem with a section of the program user can refer to documentation to
solve it.
3. User like program that they can easily make modification to.
Declaring an Array
In every program you must state each variable that you will be using and its data type, this is
called declaring variables. A data type is a given structure of the values that will be display in the
program. These are:
1. Integers – these are whole numbers whether positive or negative
2. Real – these are fraction or decimal numbers
3. Characters – This is a single letter of the alphabet, punctuation mark or symbols.
4. String – this is a collection of characters such a word, sentence or phrase.
5. Boolean value – this data type exist in two possible ways True and False.
Format of declaring and Array
Var Name of Array: Array[Size of Array] of data type;
Temp [2]
Subscript or index (that is, the position of the item in the array)
Temp is the name of the array, 2 indicates the location of the value 28.
Arrays are sometimes called subscripted variables, because the values stored in the locations of
an array are accessed via the subscript or index of the array.
Arrays are typically used to store and process a list of items. That is why, in some texts,
manipulation of arrays is sometimes referred to as list processing.
Defining Array
Like other variables in Pascal, an array must be defined before it can be used to store
information.Like other definitions, an array definition specifies a variable type and a name. But it
includes another feature i.e. size.ArrayName [Const Int Expression]DataType;
Accessing Array Elements
The items in an array are called array elements.All elements in an array are of the same type;
only the values vary. Example: array1[4] of integer= { 10, 5, 678, -400 } ;
The elements of an array can be accessed individually by specifying the name of the array,
followed by the index or subscript, which identifies the position of the element in the sequence.
Therefore, when manipulating arrays, a special variable must be declared as the index of the
array. A single letter (such as I, J, or K) is commonly used as array index. Using the index, the
array elements can be manipulated in the same way that we manipulate ordinary variables. For
example, we can assign an initial value to an array, we can read a value into an array location, we
can display values stored in arrays, and we can perform arithmetic and logical operations on the
elements in an array. Traversing the array (that is, access each element in a sequential manner)
requires a loop structure. Examples of this will follow.
Initializing Arrays
Initial values can be assigned to array locations either by reading values directly into the
locations or by use of an assignment statement. Let’s say for example, that we want to set all 10
locations of the array list to 0, initially. We would write:
Traversing Arrays
Traversing an array simply means, moving through the array in a sequential manner, visiting
each element, in order to manipulate the elements in one way or another. For example, an array
is traversed when we print the elements, or when we search the list for a particular item, or when
we sort the list of items in a particular order. In traversing an array, we must establish a loop and
increment the index within the loop in order to get to the next element.
A classic example of traversing an array is to perform a linear search. A linear search involves
examining each element in the array, one by one, starting with the first element and comparing
each element with the item/value being search for. The search ends when a match is found or
when the end of the array is reached. The following is an algorithm for performing a linear
search of an array.
Linear Search
Linear search is a simple search algorithm for searching an element in an array. It works by
comparing each element of an array. It is the most basic and easiest algorithm in computer
science to find an element in a list or an array.
Pascal
Program Header - is the first line of the program. it contains the keyword PROGRAM followed
by the name of the program. A program name cannot be the same as a variable name, it must be
unique.
Pascal Examples Explanation
Program Name; Program Sample (Input, Output); All Pascal programs must have a
program heading. The first word,
Program is compulsory.
Declarations
Const Const Pi = 3.14; A constant is a value that does
not change. You assign a value to
a constant when you create it.
Var Var Mark, count:Integer; This is called variable
Test:real; declaration. Before you can use a
Grade:Char; variable you must first declare it.
Title = Hello; Variables types include integers,
List:array[1..5] of intergers; real, characters, string and array.
Procedures and Functions will go here before the main program.
Begin Begin Denotes the start of one or more
programming statements.
Statement Read (Mark); These include:input,
Writeln(“Thank You”); Output,
If (mark >30) then grade : = ‘P’ Conditional,
Else Grade ; =’F’ Assignment,
Writeln(Grade); Loop
For count: = 1 to 5 do
Begin Begin (of a compound
statement)
Test: = Mark*count; Compound statement two or
Writeln(‘The test output is, more consecutive statement.
“test);
End; End; (of a compound statement)
Example:
Write a Pascal program to read three numbers and find their sum and product
End.
Example:
write a Pascal program to asks the user to enter his/her mark in a course, check if the mark is 50 or
more and then displays a message indicating that the student has passed the course otherwise
indicating a message the students has fail the course.