0% found this document useful (0 votes)
6 views

Unit 8

Uploaded by

zanna.graham
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Unit 8

Uploaded by

zanna.graham
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 25

UNIT 7 - PROBLEM SOLVING AND PROGRAM DESIGN

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

Num 2 Add the three numbers


together

Num 3 Output the sum of the


numbers
Algorithm
An algorithm is a sequence of precise accurate instructions for solving a problem in a finite
amount of steps.
Characteristics of an Algorithm
1. Precise (instructions or steps must be specific/accurate)
2. Unambiguous/clear (easy to read and understand)
3. A finite number of steps
4. Give correct solution at all times.
5. Show flow of control (steps should follow a proper sequence or order)
6. It must be terminate(have and end)
Pseudocode
A pseudocode is an imitation of computer program written using mathematical notation and
English like statement to describe the logic to solve a problem or carry out a procedure.
Steps for developing a Pseudocode
The input step – this is where the instruction from the user is being gathered. It is also used to
get data from outside the computer via some variables for manipulation by the Pseudocode. For
input we used Read.
E.g. Write a pseudocode to read two variables to read two numbers into variables A and B.
Read A
Read B
The processing Steps – this is where the instructions are worked through. It can involve all or
some of the following steps:
 Assignment -In these steps the values are assigned to variables.

e.g. write a assignment statement to store the value 2000.


Num = 2000

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

While Numb <> 0 do

Sum = sum + numb

End while

Print “sum of the number is “Sum”

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:

Input/Output Processing/Assignment Decision Start/Stop Flow Line


Problem 10

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:

INPUT PROCESSING OUTPUT


Rate, hours- 1. read rate, hours-worked Wages
worked 2. Calculate overtime pay, if any
3. Calculate wages
4. print wages

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

Read rate, hour-worked

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:

TestScoreRange Letter Grade


80 – 100 ‘A’
70 – 79 ‘B’
60 - 69 ‘C’
Below 60 ‘D’

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 first step is to define the problem:

INPUT PROCESSING OUTPUT


test-score 1. read test-score Test score
2. for each test score, determine
3. corresponding letter grade Letter grade
4. print test-score & 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

OR Operator - yields TRUE if at least one value is TRUE

TRUE or TRUE = TRUE


TRUE or FALSE = TRUE
FALSE or TRUE = TRUE
FALSE or FALSE = FALSE
Is any value of A is true or any value B is true, then the result of A or B is true. (Once the any of
the value is true the result is true).
A B A OR B
1 1 1
1 0 1
0 1 1
0 0 0
NOT Operator - is an unary operator - it is applied to only one value and inverts it values.
NOT TRUE = FALSE
NOT FALSE = TRUE

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

ARTHEMETIC OPERATOR RELATIONAL OPERATORS


+ Plus Sign = Equal
Minus Greater Than
*(Asterisk) < Less Than
Div – Division
/ Forward Slash >= Greater than or equal to
MOD (Module) Division (10 mod 3 – will >= Less Than or equal to
give the remainder)
% (Percentage) <> Not equal to
^ Caret – Exponentiation (3^2)

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.

3. Create a table of all the variables used in the algorithm.


4. Walk the first case through the algorithm, keeping a step by step record of the content of
each variables in the table as the data passes through the logic until the algorithm reaches
its logical end.
5. check that the expected result established in Step 2 matches the actual result developed
in Step 4.
6. Repeat the process using a different set of test data.
Example
Complete the trace able for the following algorithm, given that the number 4 is the input value X .

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

How to calculate Y when M is 1, Y = 4 -1 =3


How to calculate Y when M is 2, Y = 4 -2 =2
How to calculate Y when M is 3, Y = 4 -3 =1
How to calculate Y when M is 4, Y = 4 -4 =0
How to calculate Z = (5*3) – 1 = 15 – 1 = 14
How to calculate Z = (5*2) – 2 = 10 – 2 = 8
How to calculate Z = (5*1) – 3 = 5 – 3 = 1
How to calculate Z = (5*0) – 4 = 0 – 4 = -4
UNIT 8 - PROGRAM IMPLEMENTATION
Programming Languages
Programming is the art of writing the solution to a problem using a language that a computer can
understand. There are many programming languages that can be used to write programs or create
other kinds of software. These languages are grouped into two categories
a. Low level Language
b. High Level Language
Low Level Language
These are machine dependent that is the code written can only be understood by the particular
computer or processor that was used to write the code. These are:
1. First Generation Language (Machine Language) – uses the digits 0 and 1 that makes
up the binary code.

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.

Steps in Implementing a Program


There are five (5) steps that a programmer will take when implementing a program:
1. Create a source code. – A set of computer instructions which are written using
appropriate assembly or high level programming language.

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.

4. Execute the program – this will usually have an exe. Extension.

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.

There are two types of documentation internal and external documentation.


Internal documentation is a set of notes included within the sources code as comments. It is
oftencombined with meaningful variables names with the intention of providing potential future
programmers a mean of understanding the working of the code. Some of the key features of
internal documentation include:
a. The use of mnemonic names
b. The use of comments
c. Indentation
d. Effective use of white spaces
External Documentation – is a written text that accompanies computer software. It either
explains how it operates or how to use it, or may mean different things to people in different
roles. External Documentation can be technical or user documentation. Technical documentation
is written by technical people for technical people with how the programs work. For example the
version of the program, supporting operating system, storage required and Installation
procedures. While user documentation is concern with what the program does and how the end
uses make the program do what it is supposed to do. (User’s Manual)
Array
An array is an element of data type that is grouped together and is referred to by a single name.
One dimensional array is like a list of data or a column of data. A subscript or an index identifies
each item in the array or the size of the array, while the other column or row will indicate the
name of the array. The items (or elements) of the array are organized in sequence and can be
accessed directly by specifying their positions in the sequence, using an index or subscript. If
only one index is used, the array is called a one-dimensional array. If more than one index is
used, the array is called a multi-dimensional array.

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;

One- Dimensional Array


One-dimensional arrays are list structures (or vectors).

A one-dimensional array can be represented as follows:


To refer to the 2nd temperature value, 28 we would specify its position in the array as a subscript
of the array name. That is,

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 Name of Program (Input, Output):{program header}


Uses Crt;{ unit which allows us to use certain default commands}
{declaration section starts here}
CONST
VAR
{the declaration section that is , identify all constants and variables}
BEGIN
{the start of the program body that is executable statements}
BODY
END
{the end of executable statements}

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)

End. End. End with a full stop indicates the


very last line or the end of the
program.

NB: the semicolon is used to separate declarations and most statements.

Example:

Write a Pascal program to read three numbers and find their sum and product

Program Sum product (input, output);


Var
Val 1, val 2, val 3, sum,product;real
Begin
Write (‘Enter first number: ‘);
Readln(val 1)
Write (‘Enter second number: ‘);
Readln (val 2)
Write (‘Enter third number: ‘);
Readln (val 3)
Sum: = val 1+ val 2+ val 3;
Product: = val 1 * val 2 * val3;
Writeln (“the sum of the three numbers is, “SUM”)
Writeln (“the Product of the three numbers is, “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.

Program Marks (Input, Output);


Var
M: intergers;
Begin
Writeln (Enter your mark: ‘);
Read (m);
If m > 50 then
Writeln (‘you have passes the course’)
Else
Writeln (‘you have failed the course’)
End.

You might also like