Elementary Programming Principles 2ND Ed
Elementary Programming Principles 2ND Ed
Programming:
Programming is the process of designing a set of instructions (computer programs) which
can be used to perform a particular task or solve a specific problem.
It involves use of special characters, signs and symbols found in a particular programming
language to create computer instructions.
The programming process is quite extensive. It includes analyzing of an application,
designing of a solution, coding for the processor, testing to produce an operating program,
and development of other procedures to make the system function.
The program created must specify in detail the logical steps to be taken and the method of
processing the data input into the computer in order to carry out the specified task.
A computer program performs the following:
1. Accepts data from outside the computer as its input.
2. Carries out a set of processes on the data within the computer memory.
3. Presents the results of this processing as its output, and
4. Stores the data for future use.
Programming Languages:
A programming language is a set of symbols (a language) which a computer programmer
uses to solve a given problem using a computer.
The computer must be able to translate these instructions into machine-readable form when
arranged in a particular sequence or order.
LANGUAGE TRANSLATORS
A computer uses and stores information in binary form, and therefore, it cannot understand
programs written in either high-level or low-level languages. This means that, any program
code written in Assembly language or high-level language must be translated into Machine
language, before the computer can recognize and run these programs.
A Translator is special system software used to convert the Source codes (program
statements written in any of the computer programming languages) to their Object codes
(computer language equivalents).
1
The Translators reside in the main memory of the computer, and use the program code of the
high level or Assembly language as input data, changes the codes, and gives the output
program in machine readable code.
In addition, translators check for and identify some types of errors (e.g.,
Syntax/grammatical errors) that may be present in the program being translated. They will
produce error messages if there is a mistake in the code.
Each language needs its own translator. Generally, there are 3 types of language
translators: 1. Assembler.
2. Interpreter.
3. Compiler.
Functions of an Assembler
1). It checks whether the instructions written are valid, and identifies any errors in the
program. The Assembler will display these errors as well as the complete source and
object programs. If the program has no errors, the job control will let it run immediately,
or save the object program so that it may run it later without translating it again.
2). It assigns memory locations to the names the programmer uses.
E.g., the Assembler keeps a table of these names so that if an instruction refers
to it, the Assembler can easily tell the location to which it was assigned.
3). It generates the machine code equivalent of the Assembly instructions.
Usually, the Assembler generates a machine code only when no errors are detected.
Some of the errors include;
- Typing mistakes.
- Using the wrong format for an instruction.
- Specifying a memory location outside the range 0 – 2047.
Note. The Assembler cannot detect Logic errors. The programmer knows of these
errors only when the program is run and the results produced are incorrect (not what
the programmer expected). The programmer must therefore, go through the program
and try to discover why an incorrect result was being produced.
Interpreter
An interpreter translates a source program word by word or line by line. This allows the
CPU to execute one line at a time.
The Interpreter takes one line of the source program, translates it into a machine instruction, and
then it is immediately executed by the CPU. It then takes the next instruction, translates it into a
machine instruction, and then the CPU executes it, and so on. The translated line is not stored in
the computer memory. Therefore, every time the program is needed for execution, it has to be
translated.
Compiler
A compiler translates the entire/whole source program into object code at once, and then
executes it in machine language code. These machine code instructions can then be run on
the computer to perform the particular task as specified in the high-level program.
2
The process of translating a program written in a high-level source language into machine
language using a compiler is called Compilation.
For a given machine, each language requires its own Compiler. E.g., for a computer to be
able translate a program written in FORTRAN into machine language; the program must
pass through the FORTRAN compiler (which must „know‟ FORTRAN as well as the Machine
language of the computer).
The object code file can be made into a fully executable program by carrying out a Linking
process, which joins the object code to all the other files that are needed for the execution of
the program. After the linking process, an executable file with an .EXE extension is
generated. This file is stored on a storage media.
Points to note
♦ The job of a Compiler is much more difficult than that of an Assembler in that, a single
statement in a high-level language is equivalent to many machine instructions.
♦ The format of an Assembly instruction is fairly fixed, while high-level languages give
a lot of freedom in the way the programmer writes statements.
Functions of a compiler
A Compiler performs the following tasks during the compilation process:
1). It identifies the proper order of processing, so as to execute the process as fast as
possible and minimize the storage space required in memory.
2). It allocates space in memory for the storage locations defined in the program to be
executed. 3). It reads each line of the source program and converts it into machine
language.
4). It checks for Syntax errors in a program (i.e., statements which do not conform to the
grammatical rules of the language). If there are no syntax errors, it generates machine
code equivalent to the given program.
5). It combines the program (machine) code generated with the appropriate subroutines
from the library.
6). It produces a listing of the program, indicating errors, if any.
1. Translates and executes each statement 1. Translates all the source code statements at
of the source code one at a time. once as a unit into their corresponding object
The source code instruction is translated codes, before the computer can execute them.
and immediately obeyed by the computer A Compiler translates the entire source
hardware before the next instruction can program first to machine code, and then the
be translated. (Translation and execution code is executed by the CPU. (Translation
go together) and execution are separate phases)
2. Translates the program each time it is 2. Compiled programs (object codes) can be
needed for execution; hence, it is slower saved on a storage media and run when
than compiling. required; hence executes faster than
interpreted programs
3. Interpreted object codes take less 3. Compiled programs require more memory
memory compared to compiled as their object files are larger.
programs.
4. For an Interpreter, the syntax 4. For a Compiler, the syntax errors are
(grammatical) errors are reported and reported and corrected after the source code
corrected before the execution can has been translated to its object code
continue. equivalent.
5. An Interpreter can relate error messages 5. Once the source program has been
to the source program, which is always translated, it is no longer available to the
available to the Interpreter. This makes Compiler, so the error messages are usually
debugging of a program easier when using less meaningful.
an Interpreter than a Compiler.
3
Linkers and Loaders
Computer programs are usually developed in Modules or Subroutines (i.e., program
segments meant to carry out the specific relevant tasks). During program translation, these
modules are translated separately into their object (machine) code equivalents.
The Linker is a utility software that accepts the separately translated program modules as its
input, and logically combines them into one logical module, known as the Load Module that
has got all the required bits and pieces for the translated program to be obeyed by the
computer hardware.
The Loader is a utility program that transfers the load module (i.e. the linker output) into the
computer memory, ready for it to be executed by the computer hardware.
Syntax
Each programming language has a special sequence or order of writing characters. The
term Syntax refers to the grammatical rules, which govern how words, symbols,
expressions and statements may be formed and combined.
Semantics
These are rules, which govern the meaning of syntax. They dictate what happens (takes
place) when a program is run or executed.
Review Questions
1. Define the following terms:
(i). Computer program.
(ii). Programming.
(iii). Programming language.
2.With reference to programming, distinguish between Source program and Object
code. 3. What is the function(s) of: Assemblers, Interpreters and Compilers in a
computer system? 4. (a). What are the main functions of a Compiler?
(b). Differentiate between a Compiler and an Interpreter.
Each programming language has its own grammatical (syntax) rules, which must be obeyed
in order to write valid programs, just as a natural language has its own rules for forming
sentences.
LOW-LEVEL LANGUAGES
These are the basic programming languages, which can easily be understood by the
computer directly, or which require little effort to be translated into computer understandable
form. They include:
1. Machine languages.
2. Assembly languages.
Features of low-level languages
− They are machine hardware-oriented.
− They are not portable, i.e., a program written for one computer cannot be
installed and used on another computer of a different family.
− They use Mnemonic codes.
− They frequently use symbolic addresses.
Note. The computer can only execute instructions which are written in machine language.
This is because; it is the only language which the computer can understand. Therefore, any
program written in any other programming language must first be translated into machine
language (binary digits) before the computer can understand.
To write program statements in Assembly language, the programmer uses a set of symbolic
operation codes called Mnemonic codes.
The code could be a 2 or 3 shortened letter word that will cause the computer to
perform specific operation. E.g., MOV – move, ADD - addition, SUB – subtraction, RD -
read.
Example;
RD PAT, 15 (read the value 15 stored in the processor register named PAT)
SUB PAT, 10 (subtract 10 from the value in register PAT)
A program written in an Assembly language cannot be executed/obeyed by the computer
hardware directly. To enable the CPU understand Assembly language instructions, an
Assembler (which is stored in a ROM) is used to convert them into Machine language.
The Assembler accepts the source codes written in an Assembly language as its input, and
translates them into their corresponding computer language (machine code/ object code)
equivalent. Comments are incorporated into the program statements to make them easier
to be understood by the human programmers.
Assembly languages are machine-dependent. Therefore, a program written in the Assembly
language for a particular computer cannot run on another make of computer.
Advantages of Low-level languages
1. The CPU can easily understand machine language without translation.
2. The program instructions can be executed by the hardware (processor) much faster. This
is because; complex instructions are already broken down into smaller simpler ones.
3. Low-level languages have a closer control over the hardware, are highly efficient and
allow direct control of each operation.
They are therefore suitable for writing Operating system software and Game
programs, which require fast and efficient use of the CPU time.
4. They require less memory space.
5. Low-level languages are stable, i.e., they do not crash once written.
5
Disadvantages of Low-level languages
Very few computer programs are actually written in machine or Assembly language
because of the following reasons;
1. Low-level languages are difficult to learn, understand, and write programs
in them. 2. Low-level language programs are difficult to debug (remove errors
from).
3. Low-level languages have a collection of very detailed and complex instructions that
control the internal circuiting of the computer. Therefore, it requires one to understand
how the computer codes internally.
4. Relating the program and the problem structures is difficult, and therefore
cumbersome to work with.
5. The programs are very long; hence, writing a program in a low-level language is usually
tedious and time consuming.
6. The programs are difficult to develop, maintain, and are also prone to errors (i.e., it
requires highly trained experts to develop and maintain the programs).
7. Low level languages are machine-dependent (specific), hence non-portable. This
implies that, they are designed for a specific machine and specific processor, and
therefore, cannot be transferred between machines with different hardware or software
specifications. 8. It is not easy to revise the program, because this will mean re-writing the
program again.
STRUCTURED LANGUAGES
7
A structured (procedural) language allows a large program to be broken into smaller sub-
programs called modules, each performing a particular (single) task. This technique of
program design is referred to as structured programming.
Structured programming also makes use of a few simple control structures in problem
solving. The 3 basic control structures are:
♦ Sequence
♦ Selection.
♦ Iteration (looping).
3). COBOL (COmmon Business Oriented Language) COBOL is designed for developing
programs that solve business problems, e.g., can be used to develop commercial data
processing applications such as computer-based inventory control systems.
COBOL is mostly used where large amounts of data are to be handled, because it
supports powerful data and control structures.
COBOL programs are semi-compiled, and the intermediate code is
interpreted. A program written in COBOL language consists of 4
divisions: -
(i). Identification division: Where the programmer and the program details are
specified, e.g., program ID, programmer name, etc.
(ii). Environment division: Where the equipments to be used by the source and the object
programs are defined, e.g., the computer hardware.
(iii). Data division: Where the various files to be used by the program are
described, e.g., a description of the input files.
8
(iv). Procedure division: Where all the procedures required to manipulate/interrelate the
data into information are defined.
Advantages of COBOL.
− It is easy to read.
− It is portable, i.e., can be used on different types of computers. This is
because; it has an American National Institute standard.
American National Standards Institute (ANSI): – An international organization that
devised/ invented the group of standardized symbols used in flowcharting.
− It is widely used, and has a pool of skilled programmers.
Disadvantage of COBOL.
− The structure of a COBOL program is too long even for simple programs.
E.g., consider the following assignment statement:
DIVIDE A into B giving C.
This statement when used in BASIC language can much short „C=A/B‟. However, notice
that the COBOL statement above is more self defining.
4). FORTRAN (FORmula TRANslator)
It was developed for mathematicians, scientists and engineers. It provides an easier way
of writing scientific and engineering applications.
FORTRAN statements are mostly in form of mathematical expressions; hence, it is
useful in writing of programs that can process numeric data.
FORTRAN programs are compiled.
Advantages of FORTRAN.
− It is portable, i.e. it can be used on different types of computers.
Disadvantage of FORTRAN.
− It is not suited for business applications.
5). Ada
This language was named after the first lady programmer Ada Lovelace.
It is suitable for developing military, industrial and real-time systems.
6). CC
It is mainly used for developing system software such as the operating system
as well as developing the application packages.
It has powerful commands that permit the rapid development of programs, and
allows direct control over the hardware.
Disadvantage of C
− It is difficult to read and learn because of its strict dialect rules.
7). LOGO
LOGO was designed for educational use in which children can explore and develop
concepts through programming the movement of a pen.
8). COROL
COROL is used in Real-time processing.
COROL programs are compiled.
9). RPG (Report Program Generator)
RPG is used in report generating applications, (i.e. it is designed to facilitate the output
of reports of business data).
A Report generator is a software tool that extracts stored data to create customized
reports that are not normally/usually produced by existing applications.
10
OOPs use objects. An Object is a representation of a software entity such as a user-defined
window or variable. Each object has specific data values that are unique to it (called state)
and a set of the things it can accomplish called (functions or behaviour).
Several objects can be linked together to form a complete program. Programs send
messages to an object to perform a procedure that is already embedded in it. This process
of having data and functions that operate on the data within an object is called
encapsulation.
The data structure and behaviour of an object is specified/described by a template (called a
class). Classes are hierarchical, and it is possible to pass the data and behaviour of an
object in one class down the hierarchy.
Object-Oriented programming enables rapid program development. Every object has
properties such as colour, size, data source, etc, which can be set easily without much
effort. In addition, every object has events associated with it that can be used to trigger
certain actions, e.g. remove the window from the screen on clicking the „Close‟ button.
OOP has contributed greatly to the development of graphical user interface operating
systems and application programs.
Examples of Object-oriented programming languages are: -
• Simula
• C++
• SmallTalk
• Java
Java is sometimes associated with development of websites, but it can be used to
create whole application programs that do not need a web browser to run.
JAVA
Java is an OOP language that resembles Object C (a simplified form of C++).
The code of Java displays graphics, accesses the network, and interfaces with users via a
set of capabilities known as classes. Classes define similar states and common methods
for the behavior of an object.
JAVA programs are not compiled into machine code; instead, they are converted into a
collection of bytes that represent the code for an abstract Java Virtual machine (VM). A
Java interpreter running on a physical machine is then used to translate those bytes into
local actions, such as printing a string or drawing a button.
11
3. No translation is needed. directly). 3. Uses compiler or interpreter
(This is the computer 3. Uses an Assembler to Compiler translates all the source
language; hence, the convert the assembly code at once into object code;
computer understands it language source codes to their Interpreter translates line by line.
object code equivalents
Review Questions
1. (a). What is a Programming language?
(b). Explain the two levels of programming languages.
2. (a). What is meant by „Machine language‟?
(b). Explain why machine language programming is so error-prone.
(c). Show the difference between Machine language and Assembly language.
(d). Give two advantages and three disadvantages of Machine language
programming. 3. (a). What are High-level languages?
(b). Give the features/characteristics of high-level programming languages.
(c). Describe briefly how a program written in high-level programming language
becomes a machine code program ready for operational use.
(d). Explain the advantages and disadvantages of using a High-level programming
language for writing a program.
(e). List four examples of high-level programming languages. Indicate the application
of each language in computing.
4. (a). What is meant by program portability?
(b). Why are low-level languages not considered to be portable?
5. List 8 factors that need to be considered when selecting a programming language.
PROGRAM DEVELOPMENT
Stages involved in the program development cycle.
The process of program development can be broken down into the following
stages: 1. Problem recognition (Identification of the problem).
2. Problem definition.
3. Program design.
4. Program coding.
5. Program testing and debugging.
6. Program Implementation and maintenance.
7. Program documentation.
Problem recognition
Problem recognition refers to the understanding and interpretation of a particular
problem. The programmer must know what problem he/she is trying to solve. He/she
must also understand clearly the nature of the problem and the function of the program.
In order to understand a problem, look for the keywords such as compute, evaluate,
compare, etc. Usually, a programmer identifies problems in the environment and tries to
solve them by writing a computer program.
There are 3 situations that cause the programmer to identify a problem that is worth solving:
1. Problems or undesirable situations that prevent an individual or organizations from
achieving their purpose.
2. Opportunity to improve the current program.
3. A new directive given by the management requiring a change in the current system.
Sample problem: Develop a program that can be used to calculate/find the area of a
circle. Use the equation A = Π * r2
At the end of the problem definition, the programmer is required to write a requirements
report/document for the new program. This document will enable the programmer to come
up with a program design that meets the needs at hand.
Note: Problem definition should be done thoroughly to ensure user satisfaction, and to
facilitate the subsequent stages in the program development cycle. A failure at this stage
usually results in a system that will not work as intended, or that may not work at all.
Program design
Program design is the actual development of the program‟s process or problem solving
logic called the Algorithm.
It involves identifying the processing tasks required to be carried out in order to solve the
problem. The design stage enables the programmer to come up with a model of the
expected program (or a general framework (outline) of how to solve the problem, and where
possible, break it into a sequence of small and simple steps.
The models show the flow of events throughout the entire program from the time data is
input to the time the program gives out the expected information.
√ The processing tasks must be in order and systematic. Therefore, the programmer
identifies the processing tasks required, and the exact order in which they are to be
carried out. √ The design process does not take account of the programming language
to be used in the final product, since it only defines program logic.
√ Program design provides for easy maintenance.
Note. It is important to design programs before entering them into the computer. The
programmer should only attempt to covert a design into a program code after ensuring that
it is logically correct. If possible, check the logical order on the desk.
Some programmers produce rough and ready solutions at a Keyboard, and continue to
amend the programs until eventually the program appears to do what was expected. This is
not recommended in programming because of the following reasons:
1. The final code may not be easy to follow, since it was just cobbled
together. 2. Variable names and specific items of code may not be
documented.
3. Programs produced by continuous amendments and changing of codes mostly lead to
unforeseen side effects.
E.g., there may not have been plan for testing the program or procedures, hence, the
program may easily fail.
4. A programmer may be asked to modify the code at a later date. Without sufficient
documentation, the programmer will be forced to trace through the program in order to
gain an insight into how the program functions.
Modular programming
14
Many programs are non-monolithic (i.e., they are not usually made up of one large block
of code). Instead, they are made up of several units called modules, that work together
to form the whole program with each module performing a specific task.
This approach makes a program flexible, easier to read, and carry out error correction.
Program coding
Program coding is the actual process of converting a design model into its equivalent
program. Coding requires the programmer to convert the design specification (algorithm)
into actual computer instructions using a particular programming language.
For example;
The programmer may be required to write the program code either in Pascal, C++, Visual
Basic or Java, and develop (invent) suitable identifiers, variable names, and their data
types. However, remember that, at this stage the coding is still a Pencil and paper exercise.
The end result of this stage is a source program that can be translated into machine
readable form for the computer to execute and solve the target problem.
Example 1:
Develop a program code that would be used to solve the equation of a straight line
given by the expression: Y = mx + c
Program StraighLine (input, output);
VAR
y, m, x, c: INTEGER;
BEGIN
Writeln („Input the value of M‟);
Readln (M);
Writeln („Input the value of X‟);
Readln (X);
Writeln („Input the value of C‟);
Readln (C);
Y: = (m * x) + c;
Writeln („The value of y is:‟, Y);
END.
Pascal Code Explanation
VAR VAR is short form for Variable. A variable is a location for data in the computer
memory. This statement tells the computer that variables are about to be
declared. When a variable is declared, the computer sets aside some memory
space to store a value in the variable
BEGIN The Begin statement marks the start of the program body. Statements in
this section are executed by the computer. E.g., execution starts by asking
the user to input the
15
value of m
Writeln (‘Input the value of M’); The Writeln statement displays whatever is between the inverted
commas in the brackets.
The statements will be sent to the screen exactly the way they appear in the
brackets. This is because; the inverted commas are meant to make the
output readable on the screen. To display the value held in a variable on the
screen, remove the inverted commas and write the name of the variable in
the brackets, e.g. Writeln (y) will display the value held in the variable y.
Readln (M); The Read or Readln statement reads a value and stores it in a variable.
When the program is running, a Read/Readln statement in the code will
displays blinking cursor that indicates to the user where to type the input.
Y: = (m * x) +c; Calculates the value of y. in Pascal, the symbol ‘: =’ is called the Assignment
statement. The values on the right are calculated then the answer stored in
the variable y which is on the left of the assignment symbol.
Writeln (‘The value of y is:’, Y); The Writeln displays the value held in the variable y on the screen.
Note. Y is not within the inverted commas.
CONST A constant has been declared with a name Pi and value 3.142.
Pi = 3.142;
Writeln („Enter the radius‟); Displays on the screen the string between the inverted
commas.
Readln (Radius); Displays a blinking cursor that tells the user that an
input is needed before the program can continue.
Writeln („The Area is‟, Area); Displays the value stored in the variable Area.
Revision Questions
1. State the rules followed in coding a program. Program Testing and Debugging
After designing and coding, the program has to be tested to verify that it is correct, and any errors detected
removed (debugged).
TESTING:
Testing is the process of running computer software to detect/find any errors (or bugs) in the program that might
have gone unnoticed.
During program testing, the following details should be checked;
∙ The reports generated by the system.
16
∙ The files maintained in connection to the system‟s information requirements.
∙ The input to the system.
∙ The processing tasks.
∙ The controls incorporated within the system.
Note. The testing process is a continuous process, and it ends only when the Programmer and the other
personnel involved are satisfied that when operational, the program will meet the objectives and the growing
demands of the organization.
Syntax errors
Every programming language has a well-defined set of rules concerning formal spellings, punctuations, naming
of variables, etc. The instructions are accepted only in a specified form and and must be obeyed by the
programmer. Syntax errors are therefore, programming errors/mistakes that occur if the grammatical rules of a
particular language are not used correctly.
Examples:
i. Punctuation mistakes, i.e., if the programmer does not use the right punctuations and spaces needed by
the translator program, e.g., omitting a comma or a semicolon.
ii. Improper naming of variables.
iii. Wrong spellings of user defined and reserved words.
Reserved words are those words that have a special meaning to the programming language, and should not
be used by the programmer for anything else.
Syntax errors are committed by the programmer when developing, or transcribing the program, and can be
detected by the language translators, such as the Compiler as it attempts to translate a program. Such errors
must be corrected by the programmer before the program runs.
Semantic errors
These are meaning errors. They occur when the programmer develops statements, which are not projecting
towards the desired goal. Such statements will create deviations from the desired objectives.
Semantic errors are not detected by the computer. The programmer detects them when the program
results are produced.
Example;
a). IF GP> =1500 OR 2200 THEN
TAX: = GP - (GP * 13%)
17
b IF GP>=1500 AND GP<= 2200 THEN
TAX: = GP - (GP * 13%)
I the 1st statement, if the selection is between 1500 and 2200, the computer will pick only 1500 and 2200, and
the other values will not be touched.
In the 2nd statement, the computer will be able to pick all the values between 1500 and 2200, because of the
„AND‟ operator.
Lexicon errors
These are the error s, which occur as a result of misusing Reserved words (words reserved for a particular language).
Revision Questions.
State the three types of errors that can be experienced in program testing, and how each can be detected.
Syntax errors can be detected by the help of translators while logical errors are detected differently. Explain
FIVE methods which can be used to detect Logical errors.
DEBUGGING
The term Bug is used to refer to an error in a computer program.
Most programming errors often remain undetected until an attempt is made to translate a
program. The most common errors include:-
∙ Improperly declared Constants and Variables.
∙ A reference to undeclared variable.
∙ Incorrect punctuation.
∙ Debugging is therefore, the process of detecting, locating and correcting (removing, eliminating) all
errors (mistakes or bugs) that may exist in a computer program.
Notes
∙ Where possible, the program should be tested using the same test data that was used for desk checking.
More strict/rigid tests should be applied on the program in order to test the program to its limits. ∙ Only
Logical errors and Semantic errors can be corrected by the programmer using test data. ∙ A good program
should not crash due to incorrect data entry but should inform the user about the irregularity and request for
the correct data to be entered.
Diagnostic procedures
For complex programs, diagnostic procedures, such as Trace routines, may be used to find logical
errors. A Trace prints out the results at each processing step to enable errors to be detected
quickly.
Review Questions.
1) Differentiate between Testing and Debugging.
2) What is Dry running?
Note: Program maintenance runs parallel to the maintenance of the program documentation, i.e., any time
maintenance is carried out on the program, the documentation should also be updated to convey the right image
of the system.
Program documentation
After writing, testing, and debugging a program, it must be documented. In other words, the programmer
should describe all what he was doing during the program development stages.
19
Program documentation is the writing of supportive materials explaining how the program can be used by
users, installed by operators, or modified by other programmers.
Note. All the program development activities (i.e., from the initial stage up to the complete program) should be
documented/recorded in order to assist in the development of the program, future modification of the program,
general maintenance, machine and software conversion at a later date, and program changeover.
External documentation refers to reference materials such as use r manuals printed as booklets.
Review Questions.
1. What is program designing?
2. (a). Define program documentation.
(b). What does a program documentation contain?
3. Briefly explain how each of the following documents are useful in programming?
a) User manual / guide.
b) Reference guide.
c) Quick reference guide
4. Program documentation is different from Implementation. Explain.
5. Outline and briefly explain the stages involved in program development.
20
DEVELOPING OF ALGORITHMS
After carefully analyzing the requirements specification, the programmer usually comes up with the
algorithm. Definition of an Algorithm:
An Algorithm is a limited number of logical steps that a program follows in order to solve a
problem. A step-by step (a set of) instructions which when followed will produce a solution to a
given™ problem. Algorithms take little or no account of the programming language.
They must be precise/ accurate, unambiguous/clear and should guarantee a solution.
Note. For any given problem, the programmer must choose which algorithm (method) is best suited to solve it.
PSEUDOCODES.
A pseudocode is a method of documenting a program logic in which English-like statements are used to
describe the processing steps.
These are structured English-like phrases that indicate the program steps to be followed to solve a given
problem. The term “Code” usually refers to a computer program. This implies that, some of the words used in a
pseudocode may be drawn from a certain programming language and then mixed with English to form
structured statements that are easily understood by non-programmers, and also make a lot of sense to
programmers. However, pseudocodes are not executable by a computer.
Guidelines for designing a good pseudocode
i. The statements must be short, clear and readable.
ii. The statements must not have more than one meaning (i.e., should not be
ambiguous). iii. The pseudocode lines should be clearly outlined and indented.
iv. A pseudocode must have a Begin and an end. i.e., a pseudocode should show clearly the start and
stop of executable statements and the control structures.
v. The input, output and processing statements should be clearly stated using keywords such as PRINT,
READ, INPUT, etc.
Example 1:
Write a pseudocode that can be used to prompt the user to enter two numbers, calculate the sum and
average of the two numbers and then display the output on the screen.
START
PRINT “Enter two numbers”
INPUT X, Y
Sum = X + Y
Average = Sum/2
PRINT Sum
PRINT Average
STOP
Example 2:
Write a structured algorithm that would prompt the user to enter the Length and Width of a rectangle, calculate
the Area and Perimeter, then display the result.
Solution
Step 1: Draw the rectangle of Length (L) and Width (W).
Step 2: Write down the Pseudocode. START
PRINT “Enter Length and Width”
READ L, W
Area = L * W
Perimeter = 2 (L + W)
PRINT Area
PRINT Perimeter
STOP
Example 3:
21
Write a pseudocode that can be used to calculate the Diameter, Circumference and Area of a circle and then
display the output on the screen.
START
Set π to 3.14
Prompt the user for the Radius (R)
Store the radius in a variable (R)
Set Diameter to 2 * Radius
Set Circumference to π * 2 * Radius
Set Area to π * Sqr (Radius) PRINT Diameter
PRINT Circumference
PRINT Area
STOP
Example 4:
Write a pseudocode for a program that would be used to solve equation: E = MC 2.
START
Enter values M, C
E=M*C*C
Display E
STOP
It is important to use program control structures when writing Pseudocodes. The most common constructs are:
Looping (Repetition / Iteration) – used where instructions are to be repeated under certain conditions.
Selection – used when choosing a specified group of instructions for execution. The group chosen depends on
certain conditions being satisfied.
Example 5:
Write a pseudocode for a program that can be used to classify people according to age. If a person is more
than 20 years; output “Adult” else output “Young person”.
START
PRINT “Enter the Age”
INPUT Age
IF Age > 20 THEN
PRINT “Adult”
ELSE
PRINT “Young person”
FLOWCHARTS.
A Flowchart is a diagrammatic or pictorial representation of a program‟s algorithm.
It is a chart that demonstrates the logical sequence of events that must be performed to solve a
problem. Types of Flowcharts.
There are 2 common types of Flowcharts:
System flowchart.
A System flowchart is a graphical model that illustrates each basic step of a data processing system. It illustrates
(in summary) the sequence of events in a system, showing the department or function responsible for each
event.
Program flowchart.
This is a diagram that describes, in sequence, all the operations required to process data in a computer
program. A program flowchart graphically represents the types of instructions contained in a computer program
as well as their sequence and logic.
Note: Pseudocodes make an algorithm easier to understand. This is because; the algorithm can be read
from top to bottom without the need for jumping backwards or forwards to follow the logic of the algorithm as
in flowcharts.
PROGRAM FLOWCHARTS
A Flowchart is constructed using a set of special shapes (or symbols) that have specific meaning. Symbols are
used to represent operations, or data flow on a flowchart.
Each symbol contains information (short text) that describes what must be done at that point. The symbols are
joined by arrows to obtain a complete Flowchart. The arrows show the order in which the instruction must be
executed.
SYMBOLS USED IN PROGRAM FLOWCHARTS.
Below is a standard set of symbols used to draw program flowcharts as created by American National
Standard Institute (ANSI).
22
Terminal symbol.
∙ All Flowcharts must have a START and STOP symbol. The START/BEGIN symbol is the first symbol of a
flowchart, and identifies the point at which the analysis of the flowchart should begin. The STOP/END
symbol is the last symbol of a flowchart, and indicates the end of the flowchart.
∙ The words Begin and End (or Start and Stop) should be inserted in the Terminal
Note. The words mostly associated with I/O operations are READ and PRINT. READ describes the
entry of computer data, while PRINT relates to the printed output of information.
3. Process symbol.
- Process symbol is used to indicate that a processing or data transformation is taking place.
(Rectangle) algebraic formula or a sentence to describe processing.
The information placed within the process symbol may be an
Processing defined as a Formula/Computation Processing defined as a Sentence SUM = A +
4. Decision symbol.
(Rhombus)Yes No
5 Flow lines
Flow lines with arrowheads are used to indicate the direction of processing of the
program logic, i.e., they show the order in which the instructions are to be
executed.
The normal flow of a flowchart is from Top to Bottom, and Left to Right. Note.
Flow lines should never cross each other.
6. Connector symbol.
Sometimes, a flowchart becomes too long to fit in a single page, such that the flow lines
start crisscrossing at many places causing confusion and also making the flowchart
difficult to
understand.
A
The Connector symbol is used as a connecting point for arrows coming from different
directions. A Connector symbol is represented by a Circle, and a letter or digit is placed
within the circle to indicate the link.
Note. Connectors do not represent any operation. They are used to connect two parts of a
flowchart, indicating that the flow of data is not broken.
23
General guidelines for drawing a program flowchart
i. A flowchart should have only one entry/starting point and one exit point (i.e., ensure that the flowchart has a
logical start and finish).
ii. The flowchart should be clear, neat and easy to follow.
iii. Use the correct symbol at each stage in the flowchart.
iv. The flowchart should not be open to more than one interpretation.
v. Avoid overlapping the lines used to show the flow of logic as this can create confusion in the flowchart.
vi. Make comparison instructions simple, i.e., capable of YES/NO answers.
vii. The logical flow should be clearly shown using arrows.
Note. A flowchart should flow from the Top to Bottom of a page, and from the Left to the
Right. viii. Where necessary, use Connectors to reduce the number of flow lines.
ix. Connectors are helpful when a flowchart is several pages long, and where several loops are needed in
the logic of the flowchart.
x. Check to ensure that the flowchart is logically correct and complete.
Example 1:
Draw a flowchart for a program that can be used to prompt the user to enter two numbers, find the sum and
average of the two numbers and then display the output on the screen.
Start
X, Y
Sum = X + Y
Average = Sum/2
Stop
Example 2:
Draw a flowchart for a program that would prompt the user to enter the Length and Width of a rectangle,
calculate the Area and Perimeter, then display the result.
Start
L, W
Area = L × W
Average = 2 × (L × W)
Stop
Example 3:
Draw a flowchart for a program that can be used to calculate the Diameter, Circumference and Area of a
circle and then display the output on the screen.
24
Start
Set Pi = 3.14
Radius (R)
Diameter = 2 × Radius
Circumference = Pi × Radius × Diameter
Area = Pi × Radius × Radius
PRINT Diameter,
Circumference, Area
Stop
Example 4:
Design a flowchart for a program that can be used to classify people according to age. If a person is more
than 20 years; output “Adult” else output “Young person”.
Start
Age
Example 5: Age > 20 Yes No
Is ? PRINT Young Person
PRINT Adult Stop
Draw a flowchart for a program that would be used to classify animals according to sex. If a letter M is input,
the program should display „Male‟ otherwise it should display “Female”.
25
No
Enter Letter
Write a program using a flowchart to convert temperature from °C to °F. Fahrenheit =32 + (90 x
C/5). Start
Read Temp
in oC
Calculate oFahrenheit
F = 32 + (9/5 × oC)
Stop
Notes
∙ A flowchart must have a Start and an end.
∙ A flowchart is useful when the algorithm is short & the flowchart can fit conveniently on a single page. If the
flowchart is too large, it is recommended to use Pseudocodes for long & complicated programs.
26
i. If programs are modified in future, the flowcharts will direct the programmer on what was originally
done.
ii. When staff changes occur, the flowcharts may help new employees understand the existing
programs. iii. Flowcharts assist in program conversion when new hardware/software are acquired. d)
Effective coding.
Program flowcharts act as a guide during the program preparation stage. Instructions coded in a
programming language may be checked against the flowchart to ensure that no steps are omitted.
e) Orderly debugging and testing of programs.
Flowcharts help in detecting, locating and removing mistakes. The programmer can refer to the
flowchart as he/she re-checks the coding steps, & the logic of the written instructions.
f) Efficient program maintenance.
Flowcharts facilitate the maintenance of operating programs. They help the programmer to concentrate on
the part of the information flow which is to be modified.
Revision Exercise
1. Define the following:
Algorithm.
Pseudocode.
Flowchart
2. (a). State the various types of flowcharts.
(b). Discuss the advantages and disadvantages of flowcharts.
27
PROGRAM CONTROL STRUCTURES
Control structures are blocks of statements that determine how program statements are to
be executed. Control statements deal with situations where processes are to be repeated
several number of times or where decisions have to be made.
There are 3 control structures used in most of the structured programming
languages: a. Sequence
b. Selection
c. Iteration (looping)
IF – THEN
IF – THEN structure is used if only one option is available, i.e., it is used to perform a certain
action if the condition is true, but does nothing if the condition is false.
The general format of the IF-THEN structure is:
IF < Condition > THEN
Program statement to be executed if condition is true;
ENDIF
If the condition is TRUE, the program executes the part following the keyword „THEN‟. If the
condition is FALSE, the statement part of the structure is ignored, and the program continues
with the statements below the ENDIF.
The diagrammatic expression of the IF-THEN structure is:
28
True Continuation of program
Example 1: False
Condition? Execute statements between THEN and END IF
In a school, the administration may decide to reward only those students who attain a mean
mark of 80% and above.
No
Pseudocode Example 2:
IF Marks>80% THEN Execute statements between THEN and END IF
Flowchart
PRINT “Give Reward”
END IF
Is
Marks > 80%
? Yes
A user is asked to enter a set of positive numbers, one at a time. She enters a 0 (zero) to
indicate that she has no more numbers to enter.
Develop an algorithm to print the largest number entered.
Pseudocode
START
Prompt the user for a number, Largest
Prompt the user for another number, NewNumber
IF NewNumber > Largest THEN
Set Largest to NewNumber
ENDIF
Prompt the user for a number, NewNumber
Output („The largest number entered is‟, Largest)
STOP
As each number is entered, the algorithm checks if the number entered is larger than the
previous one. If it is larger, it is saved as the largest. If it is smaller, it is ignored, and holds onto
the largest number so far.
29
Example 3:
PROGRAM AgeTalk (Input, Output); VAR Age: INTEGER;
BEGIN {program}
Writeln („How old are you?‟);
Readln (Age);
IF Age >= 18 THEN
Writeln („You are old enough to join the army.‟);
END. {program}
Note: Compound statements can also be used with the IF – THEN structure.
Example 4:
PROGRAM Service; {*This program displays a message depending on the
number of years you have worked for a company*}
VAR Years: INTEGER;
BEGIN
CLRSCR
Writeln („How long have you been with the company?‟); Readln (Years);
IF Years > 20 THEN
Writeln („Get a Gold watch‟);
IF (Years > 10) AND (Years <= 20) THEN
Writeln („Get a Paper weight‟);
IF Years <= 10 THEN
Writeln („Get a pat on the back ‟);
END.
IF – THEN -ELSE
The IF-THEN-ELSE structure is suitable when there are 2 available options to select from.
The general format of the
IF-THEN-ELSE
Pseudocode Structure
IF < Condition > THEN
Statement 1, (called the THEN part)
ELSE
Statement 2, (called the ELSE part)
ENDIF (indicates the end of the control structure)
Flowchart Structure
TRUE
FALSE
Is
Condition?
Program continues
Execute statements between ELSE and END IF
30
When the IF-THEN-ELSE structure is encountered:
i. The Condition is tested.
ii. If the Condition is TRUE, the statements between THEN & ELSE (i.e., the THEN part)
are executed.
The ELSE part is skipped, and execution continues with the statement following
ENDIF. iii. If the Condition is FALSE, the THEN part is skipped. The statements between
ELSE & ENDIF (i.e., the ELSE part of the structure) are executed, and execution continues
with the statement following ENDIF.
After either group of statements has been executed, the program will then continue executing
the program statements after the last ENDIF.
Note: Using IF-THEN-ELSE, for any given test of the condition, only one set of statements is
selected for execution (not both statements).
Example 1:
In a football match, if a player makes a mistake which is considered serious by the rules of the
game, he/she is given a Red card. Otherwise, he/she is given a Yellow card.
Pseudocode Structure
Flowchart Structure
Write an algorithm which asks a user for two numbers; A and B, and calculates the value of A
divided by B. However, if B is 0, a message is printed which says that division by 0 is not
allowed. Pseudocode
START
Prompt the user for the two numbers, A and B
IF B = 0 THEN
Writeln („Division by 0 is not allowed‟)
ELSE
Set C to A/B
END IF
Output A, B, and C
STOP
Explanation
Suppose the user enters 1 for A and 0 for B in response to the prompt.
The algorithm will test if B=0. Since B is 0, the condition is True. Therefore, the THEN part is
executed printing the message: „Division by 0 is not allowed‟.
Suppose the user enters 20 for A and 5 for B in response to the prompt.
The algorithm will test if B=0. Since B is not 0, the condition is False. Therefore, the statements
between ELSE & ENDIF are executed (i.e., A is divided by B, and the result is stored in C).
NESTED IF
Nested IF structure is used where 2 or more options have to be considered to make a selection.
The general format of the Nested IF structure is:
Flowchart
No No No
Condition 1 Condition 2 Condition 3
Note: Each IF-THEN or IF-THEN-ELSE is terminated with the comment {ENDIF}. The number of
{End If‟s} must be equal to the number of {ELSE‟s}.
Example;
In an Olympics track event, medals are awarded only to the first three athletes
as follows: Position 1: Gold medal
Position 2: Silver medal
Position 3: Bronze medal
The pseudocode and flowchart below can be used to show the structure of the Nested IF selection.
Pseudocode
IF Position = 1 THEN
Medal = “Gold”
ELSE
IF Position = 2 THEN
Medal = “Silver”
ELSE
IF Position = 3 THEN
Medal = “Bronze”
ELSE
Medal = “nil”
ENDIF
ENDIF
ENDIF
32
Flowchart
No
No Position 1 Position 2 Position 3
No
Yes Yes
Yes
PRINT Medal
Example 1;
Write a pseudocode of a program that requests the user to type a number from 1 to 7. The
program then prints the corresponding day of the week.
Pseudocode
START
Prompt the user for a number from 1 to 7,
Read Day
CASE Day OF
1: Writeln („Sunday‟);
2: Writeln („Monday‟);
3: Writeln („Tuesday‟);
4: Writeln („Wednesday‟);
33
5: Writeln („Thursday‟);
6: Writeln („Friday‟);
7: Writeln („Saturday‟);
ELSE
Writeln („Wrong Day of the Week‟);
ENDCASE
STOP
When a CASE statement is encountered, the value of the control variable is used to determine
which group of statements is executed, e.g., if the value of Day is 5, then the group of statements
labeled 5 is selected for execution, and the statement; „Thursday‟ is printed.
After executing this group of statements, execution continues at the statement following END CASE.
NOTES:
i. The programmer should ensure that the value of the control variable appears as a label.
E.g., suppose the value entered for Day was 9. Since 9 does not label any statement
within the CASE construct, an error will result.
ii. A given label can be used on only one group of statements. E.g., 5 can‟t be used to label
two groups of statements. If this is done, the computer will not know which group to
select & unpredictable results can occur.
Example 2:
Write a pseudocode of a program that requests the user to type a number from 1 to 7.
Depending on the number entered, print the message, „It is a School day‟ or „It is on a
Weekend‟.
Pseudocode
Prompt the user for a number from 1 to 7,
Read Day
IF (Day < 1) OR (Day >7) THEN
Print („Invalid number entered ---‟, Day)
ELSE
CASE Day OF
2, 3, 4, 5, 6: Writeln („It is a School day‟);
1, 7: Writeln („It is on a Weekend‟);
END CASE
END IF
STOP
In the pseudocode above, the IF statement has been used to validate the value of Day. This
ensures that, only valid data gets processed by the CASE statement.
Otherwise, if the ELSE part is executed, we are sure that the value of Day will lie between
1 and 7 inclusive.
34
No Average Average
Example 3: 50 .. 59: Grade = „D‟ No Average Average
No No
Pseudocode 40 .. 49: Grade = „E‟
CASE Average OF ELSE
80 .. 100: Grade = Grade = „F‟
„A‟ END CASE
70 .. 79: Grade = „B‟
60 .. 69: Grade = „C‟ Flowchart
80-100? 70-79? 60-69? 50-59?
35
ITERATION (LOOPING / REPETITION) CONTROL STRUCTURES Looping refers to
the repeated execution of the same sequence of statements to process individual data. This
is normally created by an unconditional branch back to a previous/earlier operation. The loop
is designed to execute the same group of statements repeatedly until a certain condition is
satisfied.
Note. Iteration is important in situations where the same operation has to be carried out on a
set of data many times.
The loop structure consists of 2 parts:
∙ Loop body, which represents the statements to be repeated.
∙ Loop control, which specifies the number of times the loop body is to be
repeated. Types of loops:
(a). Conditional loop: - This is where the required number of repetitions is not known in advance.
Pseudocode
STEP 1: [Prompt the user for temperature in oC]
STEP 2: [Store the value in memory]
STEP 3: IF C > 0 THEN
STEP 4: [Calculate temperature in oF]
F: = 32 + (oC * 9/5)
STEP 5: [Output temperature in oC & oF]
STEP 6: [GOTO Step 1]
STEP 7: ELSE
STEP 8: GOTO STEP 9
STEP 9: END IF
STEP 9: STOP
START
Is
Calculate Fahrenheit F = 32 + (9/5 * oC)
P
in oC and oF
O
STOP
L
C > 0?
36
Unconditional loop: - This is where the execution of the instructions is repeated some specified
number of times.
Continuous (infinite/unending) loop: - This is where the computer repeats a process again
and again, without ending.
Example:
STEP 1: [Prompt the user for temperature in oC]
STEP 2: [Store the value in memory]
STEP 3: [Calculate temperature in oF]
F: = 32 + (oC * 9/5)
STEP 4: [Output temperature in oC & oF]
STEP 5: [GOTO Step 1]
As long as a number is entered for oC, the algorithm does not stop when it reaches STEP 5 but
rather transfers control to STEP 1, causing the algorithm/process to be repeated. However, a
zero (0) can be used to stop the program because; the program cannot give the Fahrenheit
equivalent to 0 oC.
Yes
Consider a program that can be used to calculate the sum of ten numbers provided by the user.
The „FOR‟ loop can be used to prompt the user to enter the ten numbers for at most 10 times.
The sum is calculated
37
through accumulation, each time the statements within the loop are executed. The accumulated
sum is them outputted at outside the loop when the controlling condition turns false.
Pseudocode
START
Sum = 0
FOR Count = 1 TO 10 DO
PRINT “Enter a Number”
READ Number
Sum = Sum + Number
END FOR
PRINT Sum
STOP
Flowchart
START
Sum = 0, Count = 1
1. The loop variable (Count) is first initialized/set to the Lower limit whose value is 1. 2. The
lower limit is then tested against the Upper limit whose value is set at 10. 3. If the lower limit
is less than or equal to 10, the program will prompt the user to enter a number N, otherwise
the computer will exit the loop.
4. After the last statement in the loop has been executed, the loop variable (count) is
incremented by a 1 and stored in the lower limit, i.e., Lower limit = Count + 1.
5. The lower limit is again tested, and if it is less than or equal to 10, the loop is repeated
until the time the lower limit will equal the upper limit.
NOTE:
The FOR loop can also be used to count downwards from the upper limit to the lower limit e.g.,
FOR count = 10 DOWN TO 1 DO
In this case, the upper limit 10 is tested against the lower limit 1.
Pseudocode for a „FOR‟ loop that counts from upper limit down to the lower limit:
FOR loop variable = Upper limit DOWN TO Lower limit DO
Statements;
END FOR
38
The flowchart extract for a FOR loop that counts
Upper Limit
Yes
The WHILE loop STOP Condition? No
Lower limit = Loop variable - 1 Statements
The „WHILE‟ loop is used if a condition has to be met before the statements within a loop
has to be executed, e.g. to withdrawal money using an ATM, a customer must have a
balance in his/her account. Therefore, it allows the statements to be executed zero or many
times.
Pseudocode Flowchart
WHILE Balance > 0 Do
Withdraw cash
Update Account
END WHILE
Update Account
Balance > 0?
No
39
Explanation
The condition balance > 0 is first tested.
If it is TRUE, the account holder is allowed to withdraw
cash. The program exits the loop once the balance falls
to zero.
Pseudocode Flowchart
Statements TRUE
REPEAT
Statements
UNTIL Condition Exit loop
FALSE
Statements preceding loop
Condition?
In REPEAT...UNTIL, the condition is tested at the end of the loop. Therefore, it allows statements
within it to be executed at least once. e.g., if REPEAT...UNTIL is used in case of the ATM cash
withdrawal, the customer will be able to withdraw the cash at least once since availability of
balance is tested at the end of the loop.
PRINT X, Y, STOP
Example 2: Quotient PRINT “Error: Division by zero
Quotient = X/Y
Pseudocode
START
PRINT “Enter athlete Name and Position”
INPUT Name, Position
IF Position = 1 THEN
Medal = “Gold”
ELSE
IF Position = 2 THEN
Medal = “Silver”
ELSE
IF Position = 3 THEN
Medal = “Bronze”
ELSE
Medal = “None”
ENDIF
ENDIF
41
ENDIF
STOP
Flowchart
START
INPUT
Name, Position Position 1? NO Medal = “None”
NO NO
Position 2? Position 3?
PRINT
Name, Position, Medal
STOP
Example 3:
The class teacher of Form 3S in a secondary school requested a programmer to design for
her a simple program that would help her do the following:
(a) Enter the names of students and marks obtained in 8 subjects – Mathematics, English,
Kiswahili, Biology, Chemistry, Business studies, Computer studies, and History.
(b) After entering the mark for each subject, the program should calculate the total and average
marks for each student.
(c) Depending on the Average mark obtained, the program should assign grade
as follows: Between 80 and 100 – A
Between 70 and 79 – B
Between 60 and 69 – C
Between 50 and 59 – D
Below 50 – E
(d) The program should then display each student‟s Name, Total marks and the Average
grade. Using a pseudocode and a flowchart, write an algorithm that shows the design of the
program. Pseudocode
START
REPEAT
PRINT “Enter student Name and subject marks”
INPUT Student name, Maths, Eng, Kisw, Bio, Chem, Business, Computer,
History SUM = Maths + Eng + Kisw + Bio + Chem + Business + Computer
+ History
AVG = SUM/8
IF (AVG >= 80) AND (AVG <= 100) THEN
Grade = “A”
ELSE
IF (AVG >= 70) AND (AVG <= 79) THEN
Grade = “B”
42
ELSE
IF (AVG => 60) AND (AVG <= 69) THEN
Grade = “C”
ELSE
IF (AVG => 50) AND (AVG <= 59) THEN
Grade = “D”
ELSE
Grade = “E”
ENDIF
ENDIF
ENDIF
ENDIF
PRINT Student name, Sum, AVG, Grade
UNTIL Count = Number of students
STOP
Flowchart
START
Sum = 0
INPUT
Student Name, Maths, Eng,
Kisw, Bio, Chem, Business,
Computer, History
COMPUTE
Sum = Maths + Eng + Kisw + Bio + Chem
+ Business + Computer + History
Avg = Sum/8
Is Is Is Is
NO NO NO NO
Avg >= 80? And Avg <= Avg >= 70 And Avg Avg >= 60 And Avg Avg >= 50 And Avg <=
100? <=79? <=69? 59?
Grade = “A” Grade = “B” Grade = “C” Grade = “D” Grade = “E”
PRINT
Studert Name, Avg,
Grade
STOP
Example 4:
43
The gross salary of employees in ZAG BOOKS ENTERPRISE is based on basic salary and
additional benefits as follows:
Employees who have worked for the company for more than 10 years receive an additional pay
of 10% to their basic salary.
Monthly salary bonus should be calculated based on monthly sales of books as follows:
Monthly sales Bonus Rate (%)
Above 500,000 15
Below 250,000 5
Draw a flowchart for a program that would be used to calculate the gross salary then
output each employee‟s basic salary, gross salary and all benefits.
Flowchart
START
INPUT
Name, Salary, Sales,
Years
Is
Years > 10?
COMPUTE
Increment = Salary * 10/100
Gross Pay = Salary + Increment
YES
YES
Pseudocode
START
INPUT Initial Deposit
INPUT Interest Rate
SET Deposit to Initial deposit (i.e., 2000)
SET Year to 0
WHILE Year <= 7 DO
Interest = Deposit x Interest rate
Total = Deposit + Interest
Deposit = Total {the new deposit}
Year = Year + 1
END WHILE
PRINT Deposit, Year
STOP
Example 6:
Draw a flowchart for a program that is to prompt for N numbers, accumulate the sum and
then find the average. The output is the accumulated totals and the average.
Flowchart
START
Sum = 0
I=1
INPUT N
Is
I<=N?
STOP
YES NO
YES
INPUT Number
Average = Sum/N
45
Assignment: Write a pseudocode for the flowchart above.
Example 7
Mutuku took a loan of Ksh. 400,000 from a local bank at an interest rate of 10% payable in
four years. Assuming you wish to develop a computer program that will keep track of
monthly repayments: Identify the input, processing and output requirements for such a
program.
Design the algorithm for the program using a simple flowchart and
pseudocode. Requirements:
Inputs - Initial amount borrowed
- Interest rate
- Number of years
Processing - equation to calculate Yearly repayments and Monthly
repayments. Output - Monthly repayments calculated by the process
Pseudocode
START
INPUT Initial amount borrowed
INPUT Interest rate
INPUT Number of years
COMPUTE
Yearly Repayments = Amount Borrowed * (1+ Interest Rate/100)
Monthly repayments = (Yearly repayments / 12)
OUTPUT Monthly repayments
STOP
46
47