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

Elementary Programming (1)

The document outlines the fundamental principles of programming, defining key terms such as computer programs, programming languages, source code, and object code. It explains the roles of language translators, including assemblers, compilers, and interpreters, as well as the differences between low-level and high-level programming languages. Additionally, it discusses the stages of program development, emphasizing problem recognition, definition, design, coding, testing, and implementation.

Uploaded by

kwavonerd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Elementary Programming (1)

The document outlines the fundamental principles of programming, defining key terms such as computer programs, programming languages, source code, and object code. It explains the roles of language translators, including assemblers, compilers, and interpreters, as well as the differences between low-level and high-level programming languages. Additionally, it discusses the stages of program development, emphasizing problem recognition, definition, design, coding, testing, and implementation.

Uploaded by

kwavonerd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 125

ELEMENTARY

PROGRAMMING
PRINCIPLES
2

DEFINITION OF TERMS
IN ELEMENTARY
PROGRAMMING
PRINCIPLES
3

Computer Program

▰ A computer program is a set of coded instructions


given to the computer, and represents a logical
solution to a problem.
▰ It directs a computer in performing various
operations/tasks on the data supplied to it.
4

Programming:
 It is a process of writing a set of coded instructions that
can be interpreted and executed by a computer in order
to solve a particular task.

 The end product of programming is known as a


program or software.

 The language used for creating a program are called


programming languages.
5

A computer program performs the


following;
 Accepts data from outside the computer
as its input.
 Carries out a set of processes on the
data within the computer memory.
 Presents the results of this processing as
its output.
 Stores the information for future use.
6

Programming Languages

Is a set of symbols (a language)


which a computer programmer
uses to solve a given problem
using a computer.
7

Source Code:
The term Source program refers to program
statements that the programmer enters in the
program editor window, and which have not yet been
translated into machine-readable form.

Source code is the code understood by the


programmer, and is usually written using a
programming language and must adhere to the
specific rules of the language in use.
8

Object Code:
This refers to a source code that has been
converted to machine readable format.

The source code is converted using a


language translator.
9

Language Translators
10

Language Translators

A Translator is special system software (Utility software) used to


convert the Source codes into their Object code equivalent.
All high level programming languages and assembly languages
must be translated so that the computer can understand and
execute the code.
Translators check for & identify some types of errors (e.g.,
Syntax/grammatical errors) that may be present in the program
being translated.
Each language needs its own translator.
11

Types of Language Translators


12

An assembler translates programs written


in Assembly language into machine code
that the computer can understand and
Assembler:
execute.

This process is known as Assembly.


13

Functions of an Assembler:
▰ Converts symbolic operation code (mnemonic) to
an object code.
▰ Allocates space in memory for the object code.
▰ Identify errors and produces a list of all errors
detected.
▰ It assigns memory locations to the names the
programmer uses.
14

A compiler converts the entire source code of a high level


language at once to machine code before execution.

This process is known as Compilation.


Compiler: Each language requires its own Compiler.

Example;
For a computer to be able translate a program written in
FORTRAN into machine code; the program must pass
through the FORTRAN compiler.
15

Functions of a Compiler:
▰ Translates the entire source code to object code.
▰ Allocates space in memory for the object code.
▰ Generates executable files.
▰ Saves executable files in a storage medium.
▰ Identifies errors detected.
▰ Stops compilation if errors are detected in the
source program.
16

Interpreter:

This is a language translator that converts each line of high-level


programming code to machine code.

It allows the processor to execute the translated line before it can


translate the next line of code.

The object code is not saved in the computer’s memory; hence an


interpreted program must always be translated every time it is run.

An interpreter performs the same functions as a compiler except that it


does not save the object code.
17

NOTE
▰An interpreter works with
spoken language, whereas
a translator works with
written materials.
18

Differences between Compilers and Interpreters


Interpreter Compiler Assembler

Place your screenshot here


Levels of Programming
Languages
20

Levels of Programming Languages


Programming languages are classified broadly into 2 major
categories;
 Low-level programming languages.
 High-level programming languages.
21

LOW LEVEL LANGUAGES.

This are programming languages


that can be directly understood by
the computer or little effort is
required to convert them to
machine-readable form.
22

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.
Examples of Low Level
languages
24

• It’s the lowest level


programming language and is
Machine
written in binary logic that
Language (1st
consists of 0’s & 1’s.
Generation •
The computer can readily
languages): 1st understand Machine code
GL (language) instructions
without any translation.
25

Advantages of Machine language.

▰ Its stable and reliable since it is closely


related to the architecture of the computer, it
hardly crashes.
▰ It is faster to execute since it no translation.
26

Disadvantages of Machine
language.
▰ It is not portable since it is designed for a
specific computer architecture.
▰ The process of writing the program is
tedious and time consuming.
▰ It is difficult to read, understand and
debug the lines of codes.

Machine language has
more disadvantages
than advantages, this
led to the development
of the assembly
language.


28
• Assembly languages were developed in order
to speed up programming (i.e., to overcome
the difficulties of understanding and using
machine languages).
• It uses symbolic representations known as
Assembly
Mnemonics in designing the program.
Language • Mnemonics are easy to remember and more
(2nd understandable than the machine code.
Generation • Example;
Languages): • 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)
29

Advantages of the Assembly


Language
▰ Easier to program in this language
compared to machine language.
▰ It is faster in execution than high level
languages.
▰ It is stable and reliable and hardly crashes.
30

Disadvantages of Assembly
Language.
▰ It is very tedious to write a
program.
▰ Difficult to read, understand and
debug the lines of codes.
▰ It is not portable since it machine-
dependent.
31

• High-level languages were


developed to solve (overcome) the
problems encountered in low-level
programming languages.
HIGH LEVEL • They are problem oriented and
PROGRAMMING machine-independent.
LANGUAGES. • The grammar of High-level
languages is very close to the
vocabulary of the natural
languages , for example English.
32

Purpose of High-level languages.


▰ To improve the productivity of a
programmer.
▰ To ease the training of new programmers.
▰ To speed up testing & error correction.
▰ To make programs easy to understand &
follow.
33

Categories of High Level


Languages
34

Third Generation Module ion Languages


(3GLs)/ Procedural or Structured Languages
• A problem is broken down into smaller components
which are then solved using specific procedures.
Module 1 • Programs are designed using procedures (Module).
• A module is a piece of code that solves part of a
Module 2
problem.
• The instructions are written in a sequence or specific
order in which they must be executed.
Module 3 • It emphasizes;
• Use of control structures in problem solving.
• Dividing a large task in to smaller sub-programs, each
performing a single task.
35

Advantages of Structured
programming
▰ It is easier to read and modify the program.
▰ Enables the user debug errors in a section of
the program.
▰ Enables the user test the program one
module after another making programming
more flexible.
36

Examples of Third Generation


Languages;
 FORTRAN.
 COBOL.
 PASCAL.
 BASIC.
 C.
 ADA.
37

• It was designed to write


mathematical programs.
Fortran(FORmula • It is used in scientific, engineering
TRANslator) and mathematical operations.
• It was the first high level
language to be developed.
38

• COBOL is designed for developing


programs that solve business problems
or commercial data processing
applications.
COBOL/ • COBOL is mostly used where large
(COmmon amounts of data are to be handled,
Business because it supports powerful data &
Oriented control structures such as;
 To prepare the payroll.
Language):  To control the inventory system.
 To process credit and debit
accounts.
39

• PASCAL is a general-purpose, high-level


programming language, which was
named after a French mathematician
Pascal
called Blaise Pascal.
• It was developed as an academic tool
to help in the teaching and learning of
structured programming.
40

BASIC is a simple general-


purpose high-level language
BASIC used in most computer
(Beginners All- processing tasks such as
purpose
developing business and
Symbolic
Instructional educational applications.
Code) It is easy to learn & use; hence,
suitable for students who wish
to easily learn programming.
41

• BASIC is a simple general-purpose high-level


language used in most computer processing
tasks such as developing business and
educational applications.
• It is easy to learn & use; hence, suitable for
C: students who wish to easily learn
programming.
• C is mainly used for developing system
software such as the operating system such
as UNIX as well as developing the
application packages.
42

• This language was named


after the first lady
ADA:
programmer Ada Lovelace.
• It is suitable for developing
military, industrial and real-
time systems.
43

• They make programming easier since they provide the


user with more in-built programming tools such as
Graphical User Interface generators.
• The programmer simply selects graphical objects called
Fourth controls on the screen, and then uses them to create
Generation designs on a form by dragging a mouse pointer.
• The languages also use application generators to
Languages generate the necessary program codes; hence, the
(4GLs) programmer is freed from the tedious work of writing
the code.
• 4GLs are used to access the data stored in database
systems; hence, they are described as the Query
languages.
44

Purpose of fourth generation


languages.
▰ To speed up the application-building process.
▰ To enable quick & easy amendments of
programs.
▰ To reduce development & maintenance costs.
▰ To make languages user-friendly.
▰ To allow non-professional end-users to develop
their own solutions.
45

Examples of Fourth Generation


Languages;
 Visual Basic.
 Delphi pascal.
 Visual COBOL (Object COBOL).
 Access Basic.
 Oracle.
46

Advantages of fourth generation


languages.
▰ They are user-based, and therefore,
easy to learn & understand.
▰ Very little training is required in order
to develop & use 4GL programs.
▰ They provide features for formatting of
input, processing, & instant reporting.
47

• The 5GL’s are designed to make a


computer solve a problem by portraying
human-like intelligence.
• The programmer does not have to worry
Fifth about how an algorithm will be
Generation implemented to solve the problem at hand.
Languages • The programmer only specifies the problem
(5GLs) to be solved and the conditions to be met,
then the code is automatically generated.
• The 5GLs are mainly used in Artificial
Intelligence (AI).
48

Examples of 5GLs.

▰ PROLOG (PROgramming in LOGic) used to developing


expert systems.
▰ LISP (List Processing) Used for developing Artificial
Intelligence (AI) systems.
▰ OCCAM Is used for developing parallel processing systems.
▰ OPS5 Is used for developing expert systems.
49
• It is a new approach to software development in
which data & procedures that operate on data
are combined into one object.
• A program is designed by using objects which
Object- can be re-used in any other program.
• An object is a component of a system that that
Oriented contains a set of data and procedures that
Programming manipulate the data.
Languages • Each object contains a set of functions it must
(OOP) accomplish known as behavior.
• The process of combining data and behavior that
operate on the data within an object is called
encapsulation.
50

Examples of OOP Languages.


▰ Simula
▰ C++
▰ SmallTalk
▰ Java
51

• Web scripting languages are mostly used


to create or add functionalities on web
pages.
• Web pages are used for creating Web sites
on the Internet where all sorts of
Web scripting advertising can be done.
languages • A web page is a hypertext document that is
created using a mark-up Language.
• A hypertext is a software that links topics
on the screen to related information and
graphics, which are accessed by the user
through clicking method.
52

Advantages of Web Scripting


Languages.
▰ They are portable since they are machine
independent.
▰ They are easy to debug because of their
structured nature.
▰ They are easy to learn and use since
statements are English like statements.
▰ They are easy to understand.
53

Disadvantages of Web Scripting


Languages.
▰ They require a lot memory space to run.
▰ They must first be translated to machine
language before execution , which slows
down their execution speed.
54

Examples of Web Scripting


Languages.
▰ Hypertext Mark-up Language
(HTML).
▰ Java Script.
▰ Visual Basic Script (VBScript).
▰ Hypertext pre-processor (PHP).
▰ Applescript.
▰ Python
55

Factors to consider when choosing


a Programming language.
 The availability of the relevant translator.
 Availability of skilled programmers.
 Ease of learning and use.
 Execution time.
 Development time.
 Maintenance.
 Documentation.
 Popularity.
56

PROGRAM
DEVELOPMENT

Program
development is the
process of creating
software.


PROGRAM DEVELOPMENT
▰ There are six stages of program
development.
Problem recognition Documentation

Problem definition

Program design

Program coding

Program testing

Program implementation
Problem recognition
▰ This refers to the understanding and
interpretation of a particular problem. To
understand a problem one has to look for key
words such as compute, evaluate, compare
etc. a programmer identifies problems in the
environment and seeks to solve them by
writing a computer program that would
provide the solution.
Circumstances that can cause the
programmer to identify a problem
▰ Opportunity to improve the current
program.

▰ A new directive given by the


management requiring a change in the
status quo.

▰ Problems or undesirable situations that


prevent an individual or organization from
achieving their purpose.
Problem definition
▰ At this stage the programmer tries to
determine or define the likely input, processing
and expected output using the keywords
outlined at the problem recognition stage.
▰ The boundaries of the expected program are
established and if several methods to solve the
same problem are identified the best
alternatives should be chosen. At the end of
the stage requirement documentation for the
Program design
▰ This is the actual development of the program’s processing
or problem solving logic called algorithm. (A limited number
of logical steps that a program follows in order to solve a
problem).
▰ The programmer comes up with an algorithm after analyzing
the requirements specifications. Some of the programs are
made up of one large block code. i.e. they are Monolithic
while others are made of several units called modules which
work together to from the whole program.
▰ In modular programming, each module performs a specific
task. This approach makes a program flexible, easier to read
and debug.
Monolithic and modular program
Program coding
▰ This is the actual process of converting a
design model into its equivalent program.
This is done by creating the program using a
particular programming language. 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.
Program in Pascal and C++
Program in Pascal Program in C++
Program AreaCircle (input, output); #include<iostream.h>
Const Pi = 22/7; double radius, area;
Var double pi = 22/7;
Radius, Area: real; main ()
Begin {
WriteIn (‘Enter the radius’); cout<<‘Enter the radius’;
ReadIn (radius); cin>>radius;
Area: = Pi *Radius *Radius; area = pi *radius *radius
WriteIn (‘The area is’, Area) cout<<‘The area is’, area;
End. return 0;
}
Explain the program codes 1
Pascal code C++ code Explanation
Program Areacircle #include<iostream.h> The header of the
(input, output); programs. The statements
in () and <> shows that
the user inputs data via
the keyboard and the
program display
information on the screen.

Const Pi = 3.142; double pi = 3.142; A constant has been


declared with a name pi
and value 3.142.
Var double area, radius; Real variables with
Radius, area:real fractional part have been
declared.
Explain the program codes 2
Pascal code C++ code Explanation
Begin { Marks the beginning of
the program body or
executable statements.

WtiteIn cout<<’Enter Display on the screen


radius’: the string between
inverted commas.

ReadIn cin>>radius; Displays a blinking


(Radius) cursor that tells the
user that an input is
needed before the
program can continue.
Explain the program codes 3
Pascal code C++ code Explanation
Area: = Pi * Radius area = pi * radius Calculates the area. Notice
* Radius * radius; the assignment statement in
Pascal is : = while in C++ it is
=
WriteIn (‘The area cout<<”The area Display the value stored in
is’, Area); is’, Area<<”∖n”; the variable Area.

End. return 0; Marks the end of the program


}
Program Testing and Debugging
▰ After coding the program has to be tested
and the errors detected and corrected.
Debugging refers to detection and
correction of errors that may exist in the
program. Program testing involves creating
test data designed to produce predictable
output. They are two types of errors (bugs)
that can be encountered when testing.
Types of errors (bugs)

▰ Syntax errors – they occur as a result of


improper use of language rules. E.g.
grammar mistakes, punctuation, improper
naming of variables etc. these errors are
detectable by translator and must be
corrected before the program runs.
▰ Logical errors – they are not detectable by
the translator. The program rules but gives
wrong out put or halts during execution.
Methods of errors detection
▰ Desk checking / dry – run.
▰ Using Debugging utilities.
▰ Using Test Data.
▰ Implementation and maintenance
Implementation.
▰ Review and maintenance.
▰ Program documentation.
Desk checking / dry – run

▰ It involves going through


the program while still
on paper before entering
it in the program editor.
Using Debugging utilities

▰ In the program editor,


you can run the
debugging utilities
during translation to
detect syntax errors.
Using Test Data
▰ The programmer carries out trial runs of the
new program. At each run he enters various
data variations and extremes including data
with errors to test whether the system will
grid to a halt. A good program should not
crash due to incorrect data entry but should
inform the user about the anomaly.
Implementation and
maintenance implementation
▰ This is the actual delivery and installation
of the new program ready for use, creating
data files and train people to use the
system. The new system will change the
way things are done hence it should be
reviewed and maintained.
Review and maintenance
▰ This stage is important because of the
errors that may be encountered after
implementation. A program may fail due
to poor use, hence proper training and
post implementation support of users
will reduce chances of having them
entering invalid data that crash the
program.
Program documentation
▰ This is writing of support materials
explaining how the program can be used
by users, installed by operators or
modified by other programmers. All
stages of program development should
be documented in order to help during
future modification of the program.
Types of documentation
1. User oriented documentation – these type
enables the user to learn how to use the program as
quickly as possible and with little help from
programmer.
2. Operator oriented documentation – meant for
computer operators. E.g. Technician. It helps them to
install and maintain the program.
3. Programmer oriented documentation – written
for skilled programmers. It provides necessary
technician information to help in future modification
DEVELOPMENT OF
ALGORITHMS
Development of algorithms

▰ Algorithms – refers to a limited


number of logical steps that a
program follows in order to solve a
problem.
Program design Tools
Algorithms can be illustrated using the following tools:
1) Pseudocodes.
2) Flowcharts.
3) Decision Tables.
4) Decision Trees.
▰ Note. For any given problem, the programmer must
choose which algorithm (method) is best suited to solve it.
Pseudocode

▰ Pseudocode – refers to a set of


statements written in a readable
language (English – like) but
expressing the processing logic of
a program.
Guidelines for designing a good
pseudocode
▰ The statements must be short, clear and
readable.
▰ Pseudocode lines should be clearly outlined
and indented clearly.
▰ It should show clearly the start and stop of
executable statements and control
structures.
▰ Statements must not have more than one
meaning.
Examples of Pseudo code
Solution
▰ Write of Pseudo code
that can be used to START
prompt the user to Print “Enter two
numbers”
enter two numbers,
Input x,y
calculate the sum and Sum – x + y
average of the two Average = sum / 2
PRINT sum
numbers and then
PRINT Average
display the output on STOP
the screen
Program flowcharts
▰ A flowchart is a diagrammatic
representation of a program in
algorithms. It uses statements and
symbols that have specific meaning.
The symbols are of different standard
shapes linked to show the order of
processing. Each shape contains note
Types of flowchart

▰ System flowchart – it’s a chart that depicts


the systems as a whole with only subsystems or
major elements shown,
▰ Program flowchart – this chart shows the
sequence of operations as carried out by a
computer program.
Most common program flowcharts

Start/Stop: denotes the beginning


and end of the program algorithm.

Direction: used to indicate the direction of


flow of the program logic.

Process: indicates that a processing or data


transformation is taking place. For example
SUM =A+B.
Most common program flowcharts

Decision: used to specify a condition. A


condition must evaluate to a Boolean
value (True or false) for the program to
execute the next instructions.

Connector: used as a connecting point or


interface for arrows coming from different
directions.

Direction: used to indicate the direction of


flow of the program logic.
Guidelines for drawing a
flowchart
▰ There should be only one entry and one exit
point of a program algorithm.
▰ Use correct symbol at each stage in the
flowchart.
▰ Avoid crossed flow lines.
▰ Be as neat and tidy in drawing as possible.
▰ General direction of flow in any flowchart is
from top to bottom, left to right.
Examples of flowchart
Solutio
n
▰ Draw a flowchart for a
program used to
prompt the user to Sum = X + Y
Average = Z + y/2

enter two numbers.


The program should
find the sum, and
average then display
the output.
Advantages of flowchart

▰ Gives programmer good visual reference


of what the program will do.
▰ Serves as a program or system
documentation.
▰ It’s easy to trace through from the start to
find the action resulting from a set of
condition.
▰ Allows programmers to test alternative
solutions to a problem without over coding
the program.
Disadvantages of flowchart
▰ There are so many different ways to draw
them.
▰ it’s difficult to remain neat and uncluttered if
the logic is complex.
▰ Constructing a flowchart is time consuming.
▰ They take up considerable space.
▰ They are difficult to amend without
redrawing.
Comparison between a pseudocode and a
flowchart
Program control
structures
Program control structures
▰ They are blocks of statements that determine
how statements are to be executed.
▰ There are three control structures namely.
▰ Sequence
▰ Selection decision
▰ Iteration (looping) repetition
Sequence
▰ In this control structure, the computer reads
instructions from a program file starting from
the first top line and proceeding downwards
one by one to the end. Hence sequential
program execution enables the computer to
perform tasks that are arranged
consecutively one after another in the code.
Example of how a
sequential programs code
execute
Begin
{Procedure
name} The program file
reader reads
Action 1
sequentially
Action 2
Statement by
statement to the
Action n end of the file

{Procedure name}
End
Selection/decision
▰ This structure is used to branch, depending on
whether the condition returns a value of True of False
(Yes or No).

For example
IF < Condition >
Then Action 1
Else Action 2
Endif.

▰ There are 4 types of selection controls used in high-


level programming.
 IF……….THEN

 IF……THEN……ELSE

 Nested IF
IF……….THEN

▰ This is used if only one option General format


is available. All other options IF < condition > Then
are ignored. For example if a Statement:

school wants to reward only EndIf


If
the students who have mean
Mark > = 80
mark of 80 and above, it will
then
be reward only those students
Print “Reward”
who have attained 80% and
EndIf
above and ignore the rest.
IF……….THEN……….ELSE
General Format
IF < Condition > THEN
▰ Used when there are two Statements 1
available options. For ELSE
example in a football Statements 2
EndIf
match a player is given a
RED CARD if he does a very The algorithem will be:-
IF fault = Serious THEN
serious mistake otherwise
Print “RED CARD”
he is given a Yellow Card. ELSE
Print “yellow Card”
EndIf
Nested IF

▰ This is used where two or more


options have to be considered to
make a selection. For example, to
award grades according to the
marks as follows

a. 80 marks Grade A
b. 60 marks Grade B
c. 50 marks Grade C
d. 40 marks Grade D
General format of Nested IF
General Format The pseudo code segment will
be:-
IF <Conditions> Then
If Marks = 80 THEN
Statement Grade = “A”
ELSE ELSE
IF <Condition> If Marks = 60 THEN
Then Grade = “B”
Statement ELSE
ELSE If marks = 50 THEN
IF Grade = “D”
<Condition>Then Endif
Statement Endif
Endif
Endif
Endif
Endif
End
Endif
103
CASE SELECTION General format
CASE x of
Label 1 : Statement1
Label 2 : Statement2

▰ It’s an alternative to the Label n : Statement n-1


ELSE
nested IF. This selection is Statement n
preferred to the Nested if End case

in order to reduce the Example:-


many line s of codes. CASE average OF
Case selection can only 80…100: Grade=“A”

be expressed using 70…79:


60…69:
Grade=“B”
Grade=“C”
integers and alphabetic 40…49: Grade=“E”
characters only. The ELSE

Boolean expression End Case


Grade=“F”

should be CASE integer


OF or CASW char OF
105
A financial institution would like to computerize its loaning
processes. To ascertain the legibility of a borrower, the system
should accept a customer’s ID number and check whether the
customer has previously defaulted the payment of any loan. If
the customer is reported to have defaulted, the message
DEFAULTER is displayed, otherwise the amount of loan
requested is granted. If the amount requested is greater than or
equal to 1 million, a repayment period of 6 years is displayed. If
the amount is greater than 500,000 and less than 1 million, a
repayment period of 3 years is displayed. Otherwise, a
repayment period of 1 year is displayed.
Draw a flowchart to represent the logic of the computerized
system. (8 marks)
106

ITERATION (LOOPING)
REPETITION
▰ THE-WHILE-
DO LOOP

▰ REPEAT……….UN
TIL LOOP

 The FOR
LOOP
Iteration (looping) repetition

▰ This is designed to execute the same


block of code again and again until a
certain condition is fulfilled. Iteration is
important in situations where the same
operation has to be carried out on a
set of data many times. There are
three main looping controls.
╺ THE-WHILE-DO LOOP
╺ REPEAT……….UNTIL LOOP
╺ The FOR LOOP
THE-WHILE-DO LOOP

▰ This repetitive structure tests the


condition first before executing the
successful code if and only if the Boolean
expression returns a true value.

Example
To withdraw money using an ATM a
customer must have a balance in his/her
account.
General format of THE-WHILE DO
LOOP
General format
While <condition>
Do
Flowchar
t Statement
End while
Withdraw cash
update account
Pseudo code
segment
While balance >0
do
Withdraw
REPEAT……….UNTIL LOOP

▰ In this structure the code is executed before


testing the condition. The repeat loop stops
when the Boolean statement returns a value. For
example in the case of ATM discussed above the
client can withdraw money until balance is zero.
Example
Pseudo code segment.
REPEAT
Withdraw cash
Update account
Until balance <0;
General format of REPEAT…………UNTIL
LOOP
Flow chart
General format
REPEAT
Withdraw cash
update account. Statement
UNTIL <condition>
The FOR LOOP

▰ This structure is used where execution of


the chosen statements has to be repeated
a predetermined number of times. For
example if a program is to calculate the
sum of ten numbers provided by the user.
The FOR LOOP can be used to prompt the
user to enter the 10 numbers at most ten
times. Once the numbers are entered the
program calculates and displays the sum.
Pseudo code of the FOR LOOP

Pseudo code
FOR count = 1 to 10 DO
writeln “Enter a number (N)”
Readln N
Sum = sum + N
End FOR
Display Sum

The counter has to be set to a start value and


sometimes to an end value.
General format of the FOR
LOOP
General format
1. format for the FOR LOOP that counts from lower limit.
For loop variables = lower limit To upper limit Do
Statements
EndFor

2. Format for the ‘For’ loop that counts from upper limit down to
lower limit
For loop variable = Upper limit Down To Lower Limit Do
Statements
EndFor
Flowchart for a For Loop that
counts upward

Loop Variable = lower Lower limit = Loop


limit variable + 1

Statement
Flowchart for a For Loop that counts
downwards

Loop Variable = Upper limit Upper limit = Loop


variable - 1

Statement
Examples of complex pseudo
codes 1
▰ Ushirika Society pays 5% interest on shares
exceeding Kshs 10,000 and 3% on shares that do
not meet this target. However no interest is paid
on deposits in the member’s bank account. Design
a pseudo code for a program that would:
a. Prompt the user for shares and deposit of a particular
member.
b. Calculate the interest and total savings.
c. Display the interest and total savings on the screen
for a particular member.
Pseudo code of examples 1

Pseudo code
Start
Input Name, share, Deposit
If share > 10000 THEN
Interest = 0.05*shares
ELSE
Interest=0.03*shares
Endif
Total savings = deposits + Interest +
shares
Print Name, Totalsaving, Interest
Stop
Flowchart of example
1

Interest = 0.03 *
shares
Interest = 0.05 *
shares

Totalsavings = deposit + shares +


interest
Examples of complex pseudo
codes 2
▰ Botswana has a population of 3,000,000
but this is falling by 4% each year. The
island of Reunion has a population of
95,000 but this is increasing by 9% each
year.
a. Draw a flowchart that predicts the year
in which the population of reunion will be
greater than that of Botswana if the
Solution of example 2
Pseudo code of example 2
Pseudo code
Start
Bts: = 3,000,000
1R: = 95,000
Year: = 0
REPEAT
Bts = Bts - (Bts * (4 / 100))
1R = 1R + (1R * (9 / 100))
Year = year + 1
UNTIL 1R > Bts
Print year
Stop
Examples of complex pseudo
▰ codes 3 that will allow the input of name of
Write a program
student marks obtained in 5 subjects (maths, English,
Kiswahili, computer, biology). The program should
calculate the total and average marks for each student
and assign the grades depending on the average marks
obtained as follows.
80 – 100 A
70 – 79 B
60 – 69 C
50 – 59 D
Below 50 E
The program should then display each student’s name,
total marks and average grade.
Pseudo code of example 3
If (AVG>60) AND (AVG<69) THEN
Pseudo code
Grade = ‘C’
START
If (AVG>50) AND (AVG<59) THEN
REPEAT
Grade = ‘D’
Print “Enter name and subject
marks” ELSE
Input Name, maths, English, Grade = ‘E”
Kiswahili, Computer, Biology Endif
Sum = Endif
Maths + English + Kiswahili + Endif
Computer + Biology
Endif
AVG = sum / 5
Print Name, Sum, AVG, Grade
If (AVG>80) AND (AVG<100)
Until count = Number of students
THEN
Grade = ‘A’
Stop
If (AVG>70) AND (AVG<79) THEN
Grade = ‘B”
Flowchart of example 3

You might also like