0% found this document useful (0 votes)
0 views121 pages

Chapter 3 Elementary Programming Principles

Chapter 3 discusses the fundamentals of computer programming, including definitions of programs, programming languages, and the translation process from source code to object code. It outlines the differences between low-level and high-level languages, detailing their advantages and disadvantages, as well as various programming paradigms such as procedural, object-oriented, and web scripting languages. The chapter also covers the stages of program development, from problem recognition to implementation.

Uploaded by

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

Chapter 3 Elementary Programming Principles

Chapter 3 discusses the fundamentals of computer programming, including definitions of programs, programming languages, and the translation process from source code to object code. It outlines the differences between low-level and high-level languages, detailing their advantages and disadvantages, as well as various programming paradigms such as procedural, object-oriented, and web scripting languages. The chapter also covers the stages of program development, from problem recognition to implementation.

Uploaded by

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

Chapter 3

Elementary programming
principles
Form three work

1
Introduction
 Human beings have evolved
from the stone age to a highly
sophisticated and advanced
society by inventing things like
the wheel, fire, transistors and
today’s ultra modern devices
like computers. The idea of
computers started way back in
the nineteenth century. The first
generation computers called
Electronic Numeric Integrator
And Calculator (ENIAC 1) were
operated by plugging wires into
a control panel that resembles
the old telephone switchboards.
Computer programming
 A program – is an organised list of statements
(instructions) that when executed, causes the
computer to behave in a predetermined manner
or carry out a defined task.
 Programming – refers to the process of
developing computer (instructions) programs
used to solve a particular task.
 A computer program – is designed using a
particular programming language. Each
language has a special sequence or order of
writing characters usually referred to as syntax.
Terms used in programming
 Source program
 Object code
 Translator
 Assembler
 Interpreter
 Compiler
Source program
 This refers to the program code that the
programmer enters in the program editor
window that is not yet translated into
machine-readable form.
Object code
 This refers to the program code that is in
machine-readable. i.e. a source code that
has been translated into machine
language.
Translator
 These are programs that
translates/convert the source program into
object code. E.g. assemblers, compliers,
interpreters etc.
Assembler
 An assembler translates a program written
in assembly language into machine
language,
Interpreter
 This translates the source program line-
by-line, allowing the CPU to execute one
line before translating the next. The
translated line is not stored in the
computer memory, hence every time the
program is executed, it has to be
translated.
Complier
 This translates the entire source program
into object code. The compiler translates
each high-level instruction into several
machine code instructions in a process
called COMPILATION and produces a
complete independent program that can
be run by the computer as often as
required without the original source
program being present.
Difference between the interpreters and compilers

Interpreters Compilers
Translates the source program Translates the entire source
one statement at a time. code at once before execution.
Translates the program each Compiled program (object
time it is run hence slower than code) can be saved on a
compiling. storage media and run as
required, hence executes
faster than interpreted
programs.
Interpreted object code takes Compiled programs require
less memory compared to more memory as the object file
compiled program. are larger.
Level of programming languages
 There are 2 major levels namely;

 Low-level languages.

 High-level languages.
Low-level languages
 These languages are classified as low
because they can be easily understood by
the computer directly or they require little
effort to translate into computer
understandable form. These languages
are hardware oriented and therefore they
are not portable. i.e. a program written for
one computer cannot be installed and
used on another.
High-level languages
 These languages are very close to the
human language (English-like) and they
can be read and understood even by
people who are not experts in
programming. These languages are
machine independent. This means that a
programmer concentrates on problem
solving during a programming session
rather than how a machine operates.
Types of low level languages
 Machine language (First generation
languages).

 Assembly languages (Second generation


languages)
Machine language
(First generation languages)
 In this language, instructions are written using binary
logic. Given that data and instructions are in binary
form, many lines of codes are needed to accomplish
even a simple task like adding two numbers i.e. a
program written in this language look like this.
11100110 00000011 19999991
00001111 10001101
10001111 11111111 10000011
The program code is hard for human to understand
but it’s easily understood by computers.
Assembly languages
(Second generation languages)
This language is close to the machines vocabulary
rather than human beings vocabulary. It was
developed in order to overcome the difficulties of
understanding and using machine language. This
language helps the programmers to write programs as
a set of symbolic operation codes called Mnemonics.
Mnemonics are basically shortened two or three letter
words. A sample program written in Assembly
language.
MOV AX, 15 (move 15 to register Ax)
SUB AX, 10 (Subtract 10 from the value Ax)
Programs written in this language require an
assembler to convert them into machine language.
Classes of high level languages
 Third generation languages (3GLS)
 Forth generation languages (5GLs)
 Fifth generation languages (5GL’s)
 Object Oriented Programming Language
(OOP)
 Web scripting languages
Third generation languages (3GLS)
 This generation languages is also called
structured or procedural languages. A
procedural language makes it possible to
break a program into components called
modules. Each performing a particular
task. Structured programming has
advantages because its flexible, easier to
read and modify.
Examples of third generation programming language

 Pascal – was developed to help in the teaching and learning of


structured programming.
 Fotran – was developed for mathematics, scientists of
programs with mathematical expressions.
 Cobol – was designed for developing programs that solve
business problems.
 Basic – developed to enable students to easily learn
programming.
 C – used for developing system software e.g. the operation
systems. Its very powerful high level language because of its
ability to provide programmer with powerful aspects/features of
low level.
 Ada – this language is suitable for developing military, industrial
and real – time systems.
Forth generation languages (4GLs)
 This generation make programming an even
easier task than the third generation language
because they present the programmer with more
programming tools. Examples of such tools are
command buttons, forms etc. the 4 GLs are easy
to learn and understand because they are user
based. The languages syntax (grammar) is
natural, near English language and use menus
to prompts to guide a non-specialist or retrieve
data with ease.
Examples of 4GLs
 Visual Basic

 Delphi Pascal

 Visual Cobol

 C++
Fifth generation languages (5GL’s)
 These languages are designed around the
concept of solving problems by enabling
the computer to depict human like
intelligence. These programs are designed
to make the computer solve the problem
for the programmer rather than
programmer spending a lot of time to
come up with the solution.
Examples of 5GL’s
 PROLOG

 MERCURY

 LISP

 OCCAM
Object Oriented Programming Language (OOP)

 The concept behind OOP languages is to look at


a program as having various objects interacting
to make up a whole. Each object has a specific
data values that are unique to it (called state)
and a set of the things it can accomplish called
(functions or behaviour). This process of having
data and functions that operate on the data
within an object is called Encapsulation.
Several objects can then be linked together to
form a complete program. OOP has greatly
contributed to development of Graphical user
interface operation system and application
programs.
Examples of OOP
 Java

 Simula

 Small talk
Web scripting languages
 These languages are used to develop or add functionalities on
web pages. Web pages are hypertext documents created in a
language called HyperText Markup Language (HTML). The
languages consist of markup tags that tell the Internet browser
that the file contains HTML-code information and is
distinguished by a file extension of HTML. The markup tags
define the various components of a World Wide Web document
such as heading, tables, paragraphs, lists etc. HTML does not
have the declaration part and control structures, hence it’s not
considered as a true programming language. Due to its
simplicity, it has many limitations and cannot be used alone
when developing functional websites. Some special blocks of
codes called Scripts may be inserted in HTML pages using
scripting languages like JavaScript, VBScript etc in order to add
functionality to HTML pages.
Examples of HTML tags and their meanings

Tag Meaning
<HTML> Marks the beginning and end of a HTML document. All other tags and text fall
</HTML> between these two tags.
<HEAD></HEAD> Marks the header part of the document.

<TITLE> Gives title of te web page. Text between this tags appears in the title bar when the
</TITLE> page is browsed.
<BODY></BODY> Marks the body part of the document.

<CENTER></ Centres text and objects on the web page.


CENTER>
<B></B> Bolds the text on the web page.

<I></I> Italicise the text.

<H1> Sets size of text on the web page with H6 displaying the smallest and H1 the
</H1> largest size.
Creating a script using Javascript 1
 Javascript is a popular scripting language.
Before writing your HTML program with a
script inserted, make sure that you have
the latest browser software installed on
your computer. Older browsers may not
have support for Javascript. If you are
using Internet Explorer, it should be
version 5.0 and above.
Creating a script using Javascript 2
 Open Notepad and key in the following program. Do not
write the numbers to the left of each line of code.
1. <HTML>
2. <HEAD>
3. <TITLE>Scripting Example</TITLE>
4. </HEAD>
5. <BODY>
6. <HI><CENTER><B>we are the world</B></CENTER><HI>
7. <SCRIPT>LANGUAGE=‘JavaScript’>
8. document.write(‘My name is strongman’);
9. alert(‘congratulations for succeeding to run this script’);
10. </SCRIPT>
11. </BODY></HTML>
Creating a script using Javascript 3
 After typing the entire
program, save your file
on the desktop as
Example.html and then
close the notepad. Notice
that the icon to your file
on the desktop look like
that of the default web
browser in your computer.

 To view the web page,


double click the icon of
the file Example.html on
the desktop. Figure right
shows as open webpage.
Explanations of JavaScript
Advantages of low-level languages
 The CPU understands machine language
directly without translation.
 They are stable and hardly crash or
breakdown once written.
 Running a program is fast, no compilation
is needed.
 They are economical in terms of the
amount of memory they use.
Disadvantages of low-level languages
 They are difficult and cumbersome to use
and learn.
 Require highly trained experts to both
develop and maintain programs.
 Debugging programs is difficult.
 They are machine dependent.
 The programs are long.
Advantages of high-level languages
 The programs are portable (not machine
dependent).
 They are user friendly and easy to use and
learn.
 They are more flexible.
 They are easy to debug.
 They provide better documentation.
 Require less time to code.
Disadvantages of high-level languages
 Program executed more slowly.

 Require larger CPU storage capacity for


compilation.

 They have to be translated to machine


readable form before
Program development
 There are six stages of program
development. They include:
Problem recognition Documentation

Problem definition

Program design

Program coding

Program testing

Program implemetation
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 organisation 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 new program is written.
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
analysing 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. This phase enable the programmer to come up with
models of the expected program. The model show the flow of
events and data throughout the entire program from input of a
program.
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
 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.
 Operator oriented documentation – meant for
computer operators. E.g. Technician. It helps them
to install and maintain the program.
 Programmer oriented documentation – written for
skilled programmers. It provides necessary
technician information to help in future modification
of program.
Development of algorithms
 Algorithms – refers to a limited number of
logical steps that a program follows in
order to solve a problem.

 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
START that can be used to
Print “Enter two numbers”
prompt the user to
Input x,y enter two numbers,
Sum – x + y calculate the sum and
Average = sum / 2 average of the two
PRINT sum
numbers and then
PRINT Average
STOP
display the output on
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 stating what the operation is.
Most common program flowcharts
 Ellipse: denotes the beginning and end of the
program algorithm.
 Parallelogram: used to denote an input or output
operation. For example, READ A,B, PRINT SUM
=A+B
 Rectangle: indicates that a processing or data
transformation is taking place. For example SUM
=A+B.
 Rhombus: 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.
 Arrow: 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
Solution  Draw a flowchart for a
program used to
prompt the user to
enter two numbers.
The program should
Sum = X + Y
Average = Z + y/2
find the sum, and
average then display
the output.
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.
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
 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
The
program file
reader
reads
Begin {Procedure name} sequentially
Action 1 statement
Action 2 by
Action n statements
End {Procedure name} to the end

of the file
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
 CASE SELECTION
IF……….THEN
General format  This is used if only one
IF < condition > Then option is available. All
other options are ignored.
Statement:
For example if a school
EndIf wants to reward only the
students who have mean
If Mark > = 80 then mark of 80 and above, it
Print “Reward” will be reward only those
students who have
EndIf
attained 80% and above
and ignore the rest.
IF……….THEN……….ELSE
General Format  Used when there are two
IF < Condition > THEN available options. For
Statements 1 example in a football
ELSE match a player is given a
Statements 2 RED CARD if he does a
EndIf very serious mistake
The algorithem will be:- otherwise he is given a
IF fault = Serious THEN Yellow Card.
Print “RED 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
Grade = “A”
Statement
ELSE
ELSE If Marks = 60 THEN
IF <Condition> Grade = “B”
Then ELSE
Statement If marks = 50 THEN
ELSE Grade = “D”
IF Endif
<Condition>Then Endif
Statement Endif
Endif Endif
End
Endif
End
CASE SELECTION
General format  It’s an alternative to
CASE x of
Label 1 : Statement1 the nested IF. This
Label 2 : Statement2 selection is preferred
Label n : Statement n-1
ELSE to the Nested if in
Statement n order to reduce the
End case
many line s of codes.
Example:- Case selection can
CASE average OF only be expressed
80…100: Grade=“A”
70…79: Grade=“B” using integers and
60…69: Grade=“C” alphabetic characters
40…49:
ELSE
Grade=“E” only. The Boolean
Grade=“F” expression should be
End Case CASE integer OF or
CASW char OF
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

Flowchart General format


While <condition> Do
Statement
End while
Withdraw cash
update account
Pseudo code segment
While balance >0 do
Withdraw cash
Update account
End while
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
Statement
Withdraw cash UNTIL <condition>
update account.
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 limit Lower limit = Loop


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 trend
continues.
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
 Write a program that will allow the input of name of
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
Pseudo code If (AVG>60) AND (AVG<69) THEN
START Grade = ‘C’
REPEAT If (AVG>50) AND (AVG<59) THEN
Print “Enter name and subject marks” Grade = ‘D’
Input Name, maths, English, ELSE
Kiswahili, Computer, Biology Grade = ‘E”
Sum = Endif
Maths + English + Kiswahili + Endif
Computer + Biology Endif
AVG = sum / 5 Endif
If (AVG>80) AND (AVG<100) THEN Print Name, Sum, AVG, Grade
Grade = ‘A’ Until count = Number of students
If (AVG>70) AND (AVG<79) THEN
Grade = ‘B” Stop
Flowchart of example 3
Practical activity 1-1
1. Open a text editor program on your computer like NotePad or
WordPad.
2. Type the following program exactly the way it is in the editor.
<HTML>
<HEAD><TITLE>This is my first a webpage</TITLE></HEAD>
<BODY bgcolor = “red”>
<H1><CENTER><B>Hello World</B></CENTER></H1>
</BODY>
</HTML>
3. Save your work as webpage.html on the desktop. Make sure
that the Save As Type box reads “All Files” before clicking the
save button in order to avoid saving a text file with two
extensions i.e. webpage.html.txt.
Practical activity 1-2
4. Close your text editor. Notice
that your file on the desktop
has the icon of the default web
browser installed on your
computer. Double click it to
view the web page! Figure right
shows a sample of the display
expected when the file is
loaded to the browser. If you
have a colour monitor, it should
look as below only that it will
have black bold text on a red
background!
5. Check your program and
change your background to
blue, save then click the
refresh button. What happens?
Review questions 1
1. Define the term computer program.
2. What is programming?
3. State three advantages of high level languages over low level languages.
4. List four examples of languages and for each, state its most appropriate
application area.
5. Why is an executable file unique when compared to any other file?
6. Differentiate between a compiler and an interpreter. Why did early
computers work well with interpreters?
7. List the various examples of programming languages per generation.
8. State one advantage of machine language over the other languages.
9. Write the following in full
A) HTML
B) OOP
10. Distinguish between source program and object code in programming.
11. Define the term encapsulation as used in object oriented programming.
Answer of review questions 1-1
1. A computer program is a set of instructions that directs a computer on how
to process a particular task.
2. Programming is the writing of computer programs.
3. A). Easier to learn and use.
B). Portable.
C). Flexible.
D). Easier to correct errors.
4. A). FORTRAN – used for developing business oriented programs.
B). COBOL – designed for developing business oriented programs.
C). Pascal – mostly used as a teaching tool in structured programming.
D). C – mostly used to create system software such as operating systems.
E). Ada – suitable for developing real-time and industrial systems.
5. It is the main file that is used to start the program.
6. A complier translates the entire source program into machine readable form
while an interpreter translates the source program to machine language
line-by-line. Interpreters were used on early computers due to memory
limitations.
Answer of review questions 1-2
7. A). First generation – machine languages.
B). Second generation – assembly languages.
C). Third generation – Pascal, C, COBOL, BASIC, FOTRAN, Ada
etc.
D). Fourth generation – Visual Basic, Delphi Pascal, Visual COBOL
etc.
E). Fifth generation languages – PROLOG, Mercury, LISP, OCCAM
etc.
8. A). The processor executes them faster.
B). They are more stable.
9. A). HTML – Hypertext Markup Language.
B). OOP – Object Oriented Programming language
10. Source program refers to a program that is not yet translated while
object code refers to the program code that is in machine readable
form.
11. Encapsulation refers to the process of joining data and instruction
together to form an object.
Review questions 2
1. Give one advantage of compiling a program rather
than interpreting it.
2. Outline at least six stages of program development
in their respective order.
3. Highlight two advantages of monolithic programs.
4. State two advantages of modular programming.
5. In what stage of the development does program
documentation fall? Justify your answer.
6. Differentiate between a flowchart and pseudocode.
7. What is a program bug?
8. Explain why it is important to test a program before
implementing it.
Answer of review questions 2-1
1. A). Interpreters translate the source program one statement at a
time while compilers translate the entire source code at once before
execution.
B). Interpreters translate the program each time it runs hence
slower than compiling. Compiled programs can be saved on a
storage media. This means that it does not require any further
transaction every time the program is run hence executes faster
than interpreted programs.
C). Interpreters translation takes less memory while compiled
programs require more memory as the object code files are larger.
2. A). Problem recognition.
B). Problem definition.
C). Program design.
D). Program coding.
E). Program testing and debugging.
F). Implementation.
Answer of review questions 2-1
3. A). They are difficult to test and debug.
B). They are difficult to modify or upgrade.
4. A). They are easy to test and debug.
B). They are easy to modify and upgrade.
5. Documentation is done at all stages of program
development.
6. A flowchart is a graphical representation of step-by-step
processing logic of a program while a pseudocode is a
set of structured-English like statements that describe
the step-by-step processing logic of a program.
7. Bugs refers to program errors.
8. To correct any syntax or logical errors.
Review questions 3
1. State the factors you would consider when
A) Writing a pseudocode
B) Drawing a flowchart
2. Using illustrations, explain at least six symbols used in
flowchart design.
3. Give one advantage of pseudocodes over flowcharts.
4. Write a pseudocode for a program that would be used
to solve the equation
E = MC2
5. Draw a flowchart 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’.
Answer of review questions 3-1
1. A). Pseudocode 2. Decision – used to represent
1). Statements must be short a decision construct.
and clear.
2). Statements should be Connector – connects logic
unambiguous. flows.
3). Should shoe start and stop.
4). Words used should be Process – indicates a
suggestive such as READ, transformation of data.
PRINT, OUTPUT etc.
B). Flowchart Input/output – shows
1). A flowchart should have program input/output.
one entry and one exit point.
2). Use correct symbols. Ellipse – indicates start/stop
3). The flow should be clearly of algorithm.
indicated using arrows.
Answer of review questions 3-2
3. Pseudocodes are
easier to write and
understand.
4. Start
Enter values form
M and C
E=M*C*C
Display E
Stop
Review questions 4
1. Define the term selection in relation to program
control structures.
2. State three types of control structures used in
programming.
3. Differentiate between looping and selection.
4. In what circumstance does looping depend on
decision?
5. List four selection controls used in writing a
program.
Answer of review questions 4
1. Selection refers to a situation where further program execution
depend one making a decision from two more alternatives.
2. Sequence, decision and iteration.
3. Looping refers to a situation where the same block of code is
executed repeatedly until a certain condition is fulfilled, while
selection refers to a situation where further program execution
depends on making a decision from two or more alternatives.
4. Looping may depend on decision if a condition has to be met
before the looping terminates or continues.
5. A). IF…THEN
B). IF….THEN…ELSE
C). Nested IF
D). Case
Revision questions 1
1. State three reasons why high level languages are better than low level
languages.
2. Explain why HTML is not true programming language.
3. List three examples of forth generation programming languages.
4. Describe the term structured programming.
5. Define the term structured programming.
6. A). State two reasons for documenting all the stages of program
development.
B). Give three types of program documentation in reference to
programming.
7. Write HTML code that would display a green background, with the words
‘Hello’ on the screen.
8. Draw a flowchart showing the general flow of the following:
A) The nested IF selection.
B) The FOR loop.
C) REPEAT….UNTIL loop.
Answer of revision questions 1-1
1. A). They are portable
B). They are user friendly
C). They are more flexible
D). They are easier to debug
2. HTML is not a true programming language because it does not
have a true format of a programming language. For example, it
does not have a declaration part and control structures.
3. A). Visual Basic
B). Delphi Pascal
C). Visual COBOL
4. Fifth generation programming languages are designed in a way that
enables programmers design programs that emulate human
intelligence.
5. In structured programming, a program is broken down into
components called modules each performing a particular task.
Answer of revision questions 1-2
6. A). Reasons for documenting
i. There may rise a need to revise or modify it.
ii. Other people may think of ways of improving your program by
studying at the documentation.
B). Types of documentation
i. User-oriented.
ii. Operator-oriented.
iii. Programmer-oriented.
7. <HTML>
<HEAD><TITLE>Hello program </TITLE></HEAD>
<BODY bgcolour = “blue”>
<H3><CENTRE><B>Hello</B></CENTER></H3>
</BODY>
</HTML>
Answer of revision questions 1-3
Answer of revision questions 1-4
Revision questions 2
1. Write a program algorithm that would enable the user
to enter student marks. The program should then
determine whether the mark entered is a pass or fail
given that the pass mark is 50.
2. 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.
3. Write a pseudocode that reads temperature for each
day in a week, in degree Celsius, converts the Celsius
into Fahrenheit's and then calculate the average
weekly temperatures. The program should output the
calculated average in degrees Fahrenheit's.
Answer of revision questions 2-1
Answer of revision questions 2-2
3. START
Input temperature in ℃
et initial day to 0
WHILE initial day 6 DO
Input temperature in ℃
F=32+(9C/5)
Initial day=initial day + 1
Cummulative = cummulative + F
END WHILE
Average weekly temperature
= cummulative/7
Print Average
STOP
Revision questions 3
1. A lady deposits 2,000 shillings in a Microfinance
company at an interest rate of 20% per annum. At the
end of each year, the interest earned is added to the
deposit and the new amount becomes the deposit for
that year. Write an algorithm for a program that would
track the growth of the deposits over a period of seven
years.
2. Mukumu 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:
A) Identify the input, processing and output
requirements for such a program.
B) Design the algorithm for the program using a simple
flowchart and pseudocode.
Answer of revision questions 3-1
1. START
Input initial deposit
Input interest rate
Set deposit to initial deposit
Set year to 0
WHILE year < 7 DO
Interest = Deposit * interest rate
Total = Deposit + interest
Deposit = Total
Year = Year + 1
END WHILE
PRINT Deposit, Year
STOP
Answer of revision questions 3-2

2. A).
Inputs – initial amount borrowed
- Interest rate
- Number of years
Processing – the equation to calculate
monthly repayments.
Output – monthly repayments calculated
by the process
Answer of revision questions 3-3
2. B).
START
Input initial loan borrowed
Input interest rate
Input number of years
Calculate yearly
repayments
Monthly repayments
= yearly repayments/12
Display monthly
repayments
STOP

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy