Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
17 views

Introduction To Programming and Algorithms

Uploaded by

merkesjacob
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Introduction To Programming and Algorithms

Uploaded by

merkesjacob
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 26

INTRODUCTION TO PROGRAMMING

1. INTRODUCTION TO PROGRAMMING
A language used by human beings to communicate is called a natural
language. English is an example of a natural language. A programming
language is used to communicate a set of instructions to a computer.
Every natural language has a set of symbols, which are used to form
sentences. Similarly, every programming language has a set of
characters, which are used to construct programs. This set of symbols
is known as character set of that language. There are two aspects to
any language: syntax and semantics. The syntax of a language is the
set of rules for constructing correct sentences in the language.
Semantics, on the other hand, associates a meaning according to
certain rules, like those used in a natural language. The different is
that in programming languages, the rules are strict and precise. The
following sentences in English are perfectly clear to the reader.

Lead is a very heavy metal


The spy lead the soldiers into a trap.

The word lead is used in both sentences and has different meanings but
there is no confusion because the meaning can be interpreted from the
context. A programming language however cannot allow such usage. There
should be no scope for ambiguity because programs have to be
interpreted correctly by the computer.

Programming concepts
A computer works by executing a set of instructions known as programs.

Program -Is a sequence of instructions a computer can execute to


perform some task.

Computer programming (programming)refers to the process of developing


computer instructions (programs) used to solve a particular task. It
involves use of special characters, signs and symbols (character set)
found in a particular programming language.

A programming language is a special set of symbols that can be


translated into a particular sequence or order to perform a specific
task. Each language has a special or order of writing characters
usually referred to as syntax.

For a computer to make use of the instructions they must be written


inform that the computer can use. I.e. that program has to be written
in a programming language.

1
syntax of a language is the set of rules for constructing correct
sentences in the language.

Semantics- on the other hand, associates a meaning according to


certain rules i.e. the interpretation of the syntax used in a
language.

2. PROGRAM DEVELOPMENT

(PROGRAM DEVELOPMENT LIFECYCLE)


The process of program development is not an easy task. Remember that
in our definition of programming, we said that the program must solve
a particular problem or accomplish a task. Hence, before developing a
program, the requirements of the eventual users and its expected
functions should be fully understood.

Program development can be broken in to the following stages;

1. problem recognition
2. problem definition
3. problem design
4. program coding
5. problem testing and debugging
6. documentation
7. program implementation and maintenance

The stages can be represented diagrammatically as shown below, giving


the idea of a step by step process.

Problem
Recognition Documentation

Problem
definition

Program
design

Program
coding
The solid arrows shows the next step in
the order of program development. Program
testing

The dashed arrows show a review of


one step with the previous to see Program
whether specifications have been met. implementation
2
Notice that the completion of one stage leads to the beginning of the
next stage. At the same time, some stages have to be continuously
reviewed in light of the step just before them to make sure that they
meet the requirements. For example, after coding, the code has to be
compared to the design to see whether it meets the design
specification. Therefore, this method becomes very expensive if the
correct requirements are not identified at each stage before it
initiated.

It is important to note that although some people consider


documentation as an independent stage, it is done at all stages of the
program development lifecycle . This is important so that the facts
are recorded when they are still fresh and in the required detail by
the programmer.

1. Problem recognition
Program recognition refers to the understanding and interpretation of
a particular problem. In order to understand a problem you need to
look for particular key words such as compute, evaluate, compare etc.
You can rewrite the problem in a more simplified way using the
keywords.
A programmer identifies problems in the environment and seeks to solve
them by writing a computer that would provide the solution. Many of
the privileges of automation that we enjoy today are as a result of
people who wrote computer programs to do the tasks. For example, the
intelligent control of traffic lights, the autopilot in aircraft and
the use of robots in industry are good examples where problems were
recognized and the computer was used as a tool to solve them. Think of
the person who after seeing the tedious nature of typing using a
manual typewriter decided to develop a word processor program!

In any given circumstance, the following three situations can 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. It can be argued that
any unexploited opportunity is a problem.
3. a new directive given by the management requiring a change in the
status quo.

2. Problem definition /analysis


In problem definition also referred to as analysis, the programmer
tries to determine or define the likely input, processing activities
and the expected output using the keywords outlined at the problem
recognition stage.

3
At the end of the stage, the boundaries of the expected program will
have been established. I.e. clear view of what the program needs to
comply must be in place. In case, several methods are identified hat
can be used to solve the same problem, them the best alternative
should be chosen.

The problem definition stage ends with the writing of a requirements


report or document for the new program. It is this document that
enables a programmer to come up with a program designed that meets the
needs at hand.

3. Program design
Program design is the actual development of the program’s processing
or problem solving logic called the algorithm. An algorithm refers to
a limited number of logical steps that a program follows in order to
solve a problem. It is the programmer who will usually come up with
the algorithm after carefully analyzing the requirements
specification. Many programs are not made up of one large block of
code i.e. they are mot monolithic. Instead, several units called
modules work together to form the whole as shown below

Modules

Program
Program boundary

Program
boundary

(a) A non modular program (b)A modular program


(Monolithic)

In modular programming, each module performs a specific task. This


approach makes a program flexible to read and carry out error
correction.
The design enables the programmer to come up with models of the
expected program from the time the data is input to the time the
program gives out expected information.

4. Program coding
Program coding is the actual process of converting a design model into
its equivalent program. This is done by recreating the program using a
particular programming language. The end result of this stage is a
source program that can be translated into a machine readable form for
the computer to excite and solve the target problem. Programs can be
written in many different programming languages e.g. C++, Pascal, and
Visual Basic etc.

4
5. Program testing and debugging
Testing is part of the procedures that ensures the program corresponds
with the original specifications, and that it works in the intended
environment.
It is the process of running software to find errors (or bugs), though
it is possible that that some errors may get through the testing
process without being found. The process of finding errors is called
debugging.

After coding, the program has to be tested and errors detected


corrected (debugged)
There are two types of errors (bugs) that can be encountered when
testing a program.

a. Syntax errors
These errors emanate from improper use of language rules. E.g. grammar
mistake, punctuation, improper naming of variables and misspelling of
the defined and reserved words. An error in language usage is called
syntax error.
Reserved words are those have a special meaning to the programming
language and should not be used by the programmer for anything else.
These errors are detectable by the translator and must be corrected
before the program runs.

b. Logical errors (semantic errors)


They are no detectable by the translator. The program runs but give
out wrong output or halts during execution. Logical errors occur when
the does not function as intended thus a program with an error –free
listing may still contain logical errors which may still contain
logical errors which produce incorrect results or cause the program to
be aborted during program execution. Such errors that occur during
program execution are sometimes called runtime or execution errors.
A logical error can lead to one of the two results.
- The program will produce wrong results but will finish
normally.
- An unusual condition will be encountered e.g. attempting to
divide by zero that lead to a premature end of the program.
This type of error is known as run-time error / execution
errors.

Program testing
There are several stages in testing a program
- desk checking
- Translator system checking.
- Program run with test data
- Diagnostic procedures.
- Full –scale (system) test with actual data

5
1) Desk checking (or dry run)
After writing the program, the programmer goes through the program on
paper to pick up any logic errors that would otherwise cause extra
work at a later stage.
This process is sometimes called a dry run

2) Translator system checking


After keying in the program, it is checked using the translator to
detect any syntax errors.
The programmer corrects these errors and re-submits the program unit
until an error-free listing is obtained.

3) Program run with test data


Trial runs with test data should include all important variations and
extremes of data, including data with errors to ensure that the
program does not ‘grind to a halt’ if incorrect data is read in.

4) Diagnostic procedures
For complex programs, diagnostic procedures, such as trace routines,
may be used to find logical errors. A trace print out the results at
each processing step to enable errors to be corrected quickly. If a
trace routine is not available, the programmer can insert instructions
in a program to print out intermediate result at key points.

5)System test with actual data


as part of the ‘acceptance trials’ new programs are usisually run in
parallel with the existing system for a short time so that results can
be compared and adjustments made. The system test is made using actual
data.

TEST DATA
Is data read in a program to verify accuracy of program processing
basing on original design specifications.

Categories of test data.

Normal data
This includes the most general data for which the program was
designed.

Extreme data
These test the behaviour of the program when valid data at the upper
or lower limits of acceptability are used. For example for numerical
data, very large or small values could be used.

Exceptional data
Programs are usually designed to accept a certain range or class of
inputs. If ‘illegal’ data is used, the program should be capable of

6
rejecting it rather than attempting to process it to avoid getting
wrong results.
NB
Real data- data intended to be used by the program i.e. data for which
the program is designed for.

Dummy data- data which is not real i.e. data not intended to be used
by the designed program.

6. program implementation and maintenance


Implementation refers to the actual delivery and installation of the
program for use. New programs will obviously change the way things are
done when implemented hence the need for review and maintenance.

Review and maintenance


Review and maintenance is important because of the errors that may be
encountered after the program has been implemented or exposed to
extensive use. A program may also fail not because of poor development
but due to poor use. Therefore, proper training and post
implementation support of users will always reduce the chances of
having them enter invalid data that can crash the program.

7. Program documentation
The documentation is the writing of support materials explaining how
the program can be used by the users, installed by the operators or
modified by other programmers. All stages of program development
should be documented in order to help during future modification of
the program.
Documentation can be for user of the program (user manuals ) or for
the other programmer who might modify the program in
future(technical / program manuals).

3.HISTORY OF PROGRAMMING LANGUAGES

(LEVELS OF PROGRAMMING LANGUAGES)


(EVOLUTION OF PROGRAMMING LANGUAGES)
1. Machine languages
2. Assembly languages
3. Third generations languages (3GLs)
4. Forth generations languages (4GLs)
5. Fifth generations languages (5GLs)

NB: Both the machine and assembly languages are referred to as low-
level languages
While other are referred to as High Level languages.

7
1. Machine languages (First generation languages)
These were the 1st primary languages to be used. The program
instructions were written using binary digits (0’s and 1’s). The
computer, being driven by electricity, is a bi-state device i.e. the
internal circuitry is either in an “ON” or “OFF” state. When carrying
out a given task, the computer’s internal circuits will keep on
changing state from OFF to ON and vice versa.
When a program was written in machine language, it directly addresses
the internal circuit of the machine. It is directly addresses the
internal of the machine. It is so called because it is the language
that the “understand”.
The machine language had the advantage of fast program execution since
translation was not required, and also the ability of the programmer
to directly address the control internal circuits of the computer. On
the other hand, tracing of errors in a program written in machine
language was extremely difficult. Writing the program itself was time
consuming and cumbersome and the programmer had to be an expert on the
internal workings of the computer. Also program written in machine
code are not portable i.e. machine.
Also program written in machine code are not portable i.e. are machine
dependent because CPU’s have different machine codes e.g. those for
Intel Pentium processors may differ from Motorola or Cyrix processors.
Therefore before decoding the meaning, a programmer has to find out
which CPU the program was written.

Also given that data and instructions are in binary form, many lines
of code are needed to accomplish even a simple task like adding two
numbers. A program written in machine might look like this;

11100011 00000001 10000011


00011100 10001101
10001111 11111000 10000001

Advantages of machine languages


- Execution is faster because program codes are in machine
language.
- It is quite efficient since no translation time required.
- The programmer directly addresses the internal circuit of the
computer.

Disadvantages of machine languages


- Difficult to read, write and understand.
- Difficult to debug (tracing errors) due (to lack of debugging
aids)
- Not portable (were machine dependent)
- Time consuming and cumbersome in the writing of programs.

2. Assembly languages (second generation languages)


8
Assembly languages were developed in order to overcome the
difficulties of understanding and using machine languages.
These languages replaced machine languages because they were much
easier to use. They involved the programmer writing the program
instructions using “Mnemonics” or symbolic codes e.g. using words like
SUB to represent “SUBTRACT” made by the computer manufacturers. They
were provided with an assembler, a program used to translate program
instructions written in these i.e. assembly languages to machine
languages for execution. They made the task of writing programs easier
for the programmer and were time saving compared to machine languages.
On the other hand, one could not use these languages on a different
type of machine i.e. they were machine specific. They were slower in
program execution than machine languages and the programmer still hand
to be an expert in the computer internal workings.

Mnemonics are basically shorted two or three letter words. A program


written in assembly language may look as follows;
MOV AX, 15 (move 15 to register AX)
SUB AX, 10 (subtract 10 from the value in AX)

Key:
MOV-move;
SUB-subtract;
AX- data register

The first line in the code means over the value 15 into the processor
register with the name AX. The second line tells the computer to
subtract 10 from the value in register AX.

Programs written in assembly language require an assembler in order to


convert them into machine language that the computer can understand.

Advantages of machine languages


- It is readable both by man and machine.
- It runs faster because it is machine specific and closer to
machine code
- Concise with few instructions and consequently needed smaller
storage space for code.
- It is quite efficient with short translation time, execution time
and storage space requirement.

Disadvantages of machine languages


- Difficult to read, write and understand.
- Difficult to debug due (to lack of debugging aids)
- Not portable (were machine dependent)
- Programs took longer to code due o intricate nature of the
language.
- Back up could not be generated due to portability problem.

9
High-level languages
High –level languages are very close to human language (English -like)
and they can be read ad understood even by people who are not experts
in programming. There are many types of high-level languages and each
of them was developed to address a particular problem-solving domain
while others came due to advancement in technology. These languages
are machine independent. This means that a programmer concentrates on
problem solving during a programming session rather than on problem
solving during a programming session rather than how a machine
operates.

High level languages can be classified into five groups;


1. Third generation languages (3GLs)
2. Fourth generation languages (4GLs)
3. Fifth languages (5GLs)
4. Object oriented languages (OOPs)
5. Web scripting languages

3.Third generation languages (3GLs)


Third generation languages (3GLs) are also called structured or
procedural languages. A procedural language makes it possible to break
a program into components each performing a particular task. This is
referred structured programming. The structured programming approach
emphasizes the following;
1. Large programs can be broken down into smaller sub-programs each
performing a single task.
2. Use of a few simple control structures in problem solving. These
control structures include sequence, selection and iteration as
covered later.

Structured programming offers many benefits because it is flexible,


easier to read and modify. Examples of third generation programming
languages include:

Pascal
Pascal was initially developed as an academic language, to help in the
teaching and learning of structured programming.
FORTRAN (FORmula TRANslator);
This language was developed for mathematicians scientists and
engineers. It enables writing of programs with mathematical
expressions.
COBOL( Common Business Oriented Language);
This language is designed for developing programs that solve business
problems e.g. developing data processing applications such as
computer-based inventory control systems.

BASIC(Beginners All-purpose Symbolic Instructional Code).


This language was mainly developed to enable students to easily learn
programming. Basic is a simple general purpose language used for
developing business and educational applications. Because of its

10
simplicity, it is a powerful tool for students who wish to learn
programming. It was first high-level language that was available that
was available for microcomputer users.

C
This is a programming language mainly used for developing system
software such as the operating system. It is one of the most popular
and powerful high-level languages in the business world because of its
ability to provide the programmer features of low-level languages and
at the same time easily understandable as a high level language.

Ada
This language was named after the first lay programmer, Ada Lovelace.
Ada is suitable for developing military, industrial and real-time
systems.

4. Fourth generation languages (4GLs)


Fourth generation languages make programming an even easier task than
the third generation languages they present the with more programming
tools. E.g. command buttons forms etc. The programmer selects
graphical objects on the screen called controls then uses them to
create designs on a base form The programmer may also use an
application generator that works behind the scenes to generate the
necessary code, hence the programmer is freed from the tedious work of
writing the code.
Examples of Third generation languages are Visual Basic, Delphi Pascal
and Visual COBOL.
Fifth generation languages (5 GLs)
Fifth generation 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 problems
for the programmer rather than programmer spending a lot of time to
come up with the solution. With such languages, the programmers only
worries about what problem needs to be solved and what conditions need
to be met without worrying, about how to implement an algorithm to
solve them. Examples of these languages are those used in artificial
intelligence like PROLOG, mercury, LISP, and OCCAM.

Advantages of low-level languages


1. The CPU understands machine languages directly without
translation.
2. The processor executes them faster because complex instructions
are already broken into smaller simpler ones.
3. Low level languages are stable and hardly crash or break down
once written.

11
Disadvantages
2. Low level languages are difficult and cumbersome to sue and
learn.
3. They require highly trained experts both to develop and maintain
programs.
4. Removing errors (debugging) in low level language programs is
difficult.
5. Low level programs are machine dependent i.e. they are not
transferable from one hardware or software platform to another.

Advantages of high level languages


1. High level languages are portable ie. They are transferable from
one computer to another.
2. High level languages are user friendly and easy to use and learn.
3. High level languages are more flexible, hence they enhance the
creativity of the programmer and increase productivity in the
workspace.
4. High level languages are far much more easy to correct errors
(debug).

Disadvantages of high level languages

Their nature encourages use of many instructions in a word or


statement hence the complexity of these instructions cause slower
program processing.
They have to interpreted or compiled to machine readable form before
the computer can execute them.

4.TYPES OF PROGRAMMING LANGUAGES

a. Unstructured Languages
Are languages that have one entry and one exit point.
The program flow is sequential during execution of instructions

They are also known as imperative languages. They evolved from early
machine code and they have benefits of enhancing programmer
productivity and portability by defining the machine independent
programming environment.

b. Structured programming languages


The programs are based on control structures and it uses indentations
to improve readability. Structured programming expands on procedural
languages in that subroutines have their own local variables and for
the most parts, are completely independent. Structured programs have
the single-entry, single-exit property. This feature helps in reducing
the number of paths for flow of control. It is easier to read,
understand, debug and maintain because the programs are written in
small blocks which are linked together to one big program.

12
c. Object oriented programming languages
In object oriented programming, data is declared as part of the code
with object oriented programs, data and code, that is methods that
operate on your data, suddenly become one. Object is a combination of
code and data together that can be treated as a unit, i.e.
object = code + data.

Three features of OOP are:


Encapsulation is the ability to combine data and code procedures)
that operate on it into self contained entities called
objects.
Inheritance Is the ability for object for object(parent) to have
attribute similar to another object (offspring).
Polymorphism Gives code the ability to act on may different objects,
or be shared b may different related objects.

The main benefits of OOP are;


1. Simplification Designing a program is easier because objects
correspond more closely to real world entities.
2. Reusability Because objects are related so closely to the data
they operate on, it is possible to reuse old, reliable in new
programs.
3. Reparability While updating programs based on object oriented
technology, so that a change which in the easier to maintain.
4. Are faster and smaller programs which are easier to maintain.

Languages used in OOP, include C++, Visual Basic and Turbo Pascal for
windows.

Factors to consider when determining programming language to use

1. The nature of the problem.


Each program has a language most suited to its application.
Languages available on the computer. Many languages can be applied in
more than one area. e.g. PASCAL can be used for commercial data
processing, text processing and scientific application.

2. Efficiency of the language


By this, we mean compiler speed, object program size and execution
speed. Some language compile faster with less object code, for
instance assembly language.

3. Trained manpower
Available, trained manpower on the market that can use the available
language.

13
4. Portability of program
Programming for programs enables a system program developed on one
computer to run on another computer.

5. Structure and readability


6. Maintainability\ flexibility
7. The frequency of upgrading the language, how up-to-date it is
8. Specification of computer installation
e.g. memory size can limit the choice of a language to be used.
Some languages cannot run on a memory less than 64k. processor
speed, multiprocessor capability.

5. CHARACTERISTICS OF PROGRAMMING LANGUAGES


1. Portability
The extent to which language features support the transfer of a
program from one hardware or software platform to another.

Visual Basic can only run on windows environment but not in Unix (it
is not portable)

To make software portable, it must be written using non-system


dependent constructs except where system dependent constructs are
encapsulated.

2. maintainability
The extent in which a programming language features support source
code that can be modified to satisfy new requirements or to correct
errors.

Programs written in Assembly language are not maintainable.

3. Clarity of source code


Is the extent in which inherent language features support source code
that is readable and understandable and that clearly reflects the
underlined logical structure of the program.
e.g. machine language source code is readable and understandable.

4. expressivity
It is the capability of a programming language to express solution of
a problem in
(a)closest way to the original problem formulation.
(b) in a clear natural and concise way.
(c) in terms of other sub programs.
e.g. programs using routines / sub programs are more expressive than
languages without them.

5. Generality

14
A good programming language should support construction of instruction
codes which to a great extent solve general problems in addition to
task they were designed to solve

6. Code reuse
It is mostly supported by generality. e.g. in the use of sub routines.

DESCRIPTION OF TERMS USED IN PROGRAMMING

Source program
The term source refers to the program code that the programmer entered
in the program editor window that is not translated into machine
readable form. The source program is usually created using a
particular programming language discussed later.

Object Code
The term object code refers to the program code that is in machine
readable. A source code that is not in machine readable form must be
translated into object code.

Translators
The term translator is used to refer to language processors such as
assemblers, interpreters and compilers that converts the source
program into object code.

Assembler
An assembler translates assembly language into machine language that
the computer can understand and execute.

Interpreter
An interpreter 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. It means that
every time the program is needed for execution, it has to be
translated. This method of translating programs was very common in
early computers that did not have enough memory to store the object
code as a file that can be executed later.

Compiler
A compiler translates the entire source program into object code. The
object code file can be made into a fully executable program by
carrying out process known as linking 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 (application file) is
generated. This file is stored on a storage media such as disk with a
name that has a unique extension(.EXE) Examples of executable files
are Microsoft Word etc.

15
The difference between the interpreters and compilers are as below.

Interpreters Compilers
1. Translates the source 1. Translates the entire source
program one statement at code at once before
a time execution.

2. Translates the program 2. Compiled program (object


each time it is run code) can be saved on a
hence slower that storage media and run as
compiling. required, hence executes
faster that interpreted
programs.

3. Interpreted object code 3. Compiled programs require


takes less memory more memory as the object
compared to complied file are larger.
program

INTRODUCTION TO ALGORITHMIC PROBLEM SOLVING;

Algorithm can be defined as a general language independent set of


actions intended to perform a specific task.
IT is a step by step plan that will result to the solution of a
problem.

Characteristics of an algorithm
1. Algorithms are well ordered.
2. Algorithms are unambiguous operations.
3. Algorithm have effectively computable results
4. algorithms produce a result
5. Algorithms halts in a finite amount of time

1. Algorithms are well ordered.


Since an algorithm is a collection of operations all the
instructions must know the collect order in which it executes the
instructions.

2. Algorithms are unambiguous operations.


Each operation in an algorithm must be efficiently clear so that it
does not need to be simplified. Given a lot of numbers you can
easily order them from the largest to the smallest with the simple
instruction – sort.

3. Algorithm have effectively computable results

16
Each operation of an algorithm must be something that computer can
able to do (a number should not be divided by zero since the answer
is infinite)

4. algorithms produce a result


only algorithm which produce results can be verified.

5. Algorithms halts in a finite amount of time


Algorithms should be composed of a finite number of operations and
should complete set steps in a finite amount of time.
Example – an algorithm to print integer greater than 1 can print
infinite integers running to millions i.e. the program will run
forever.

CONVENTIONS USED IN WRITING ALGORITHMS

The following are conventions used in writing algorithms.


1. Name of the algorithm
Every algorithm is given a name which reflects the task performed by
it.

2. Introductory comments
Task performed by algorithm is described briefly. Any assumptions
made by the algorithm are mentioned here along with variables used and
their data types.

3. Steps
It is made up of a sequence of numbered steps each step by step s
preceeded by a brief comment describing its function. If a step is
composed of several statements they are executed in a left to right
manner.

4. Comments
Can be included within the body of step by step enclosing them in
parenthesis.

Guidelines for designing a good pseudocode


1. The statements must be short, clear and readable.
2. The statements must be not have more than one meaning
i.e. should be unambiguous
3. The pseudocode lines should be clearly outlined and
indented clearly.
4. A pseudocode should show clearly the start and stop
of executable statements and the control structures.
5. The input, output and processing statements should be
clearly stated, using keywords such as PRINT, READ,
INPUT etc.

Example

17
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

The following algorithm computes average of n numbers

Algorithm computes average of n numbers


The variables are
n : numbers of values entered; type integer
sum : sum of values; type integer;
count: denotes the numbers of values processed so
far;type integer
number: stores the value entered; type integer;
average: the average of n numbers; type real;

STEP 1: [input the number of data items]


Read n

STEP 2: [continue processing if n is positive]


If n>0
Perform steps 3 onwards
Else
Ext

STEP 3: [initialize]
Sum = 0
Count = 0

STEP 4: [read and add the numbers]


Repeat while count < n
Read number
Sum = sum + number
Count = count + 1

STEP 5: [compute the average]


Average = sum/n

STEP 6: [finished]

18
Exit

Algorithm writing tools

There are different ways of presenting an algorithm. They include


- flowchart
- pseudocode
- Jackson structured diagrams (JSDs)
- Decision tables
- Data flow diagrams (DFD)

FLOW CHARTS
A flow chart is a pictorial representation of an algorithm. It shows
the logic of the algorithm and flow of control. The flow chart uses to
represent specific actions and arrows to indicate the flow of control.
The flowcharts are language independent and constitute a very general
way of representing an algorithm.

The symbols used are as follows

Start or stop/ terminator

The symbol represents the beginning and end of a flow chart

Input/ output symbol

The symbol represents a particular input or output operations.


Used to enter data into a program and display the result of
computation by the program.

Processing symbol

It is used to represent a process / operation e.g. assignment


statement, data manipulation etc.

Direction symbol

It is used to indicate the process flow. I.e. the direction of flow of


a flow chart.

Connector

It is a symbol used to represent an exit from one part of a program or


an entry to another to another part of the program.

19
Decision symbol

It is used to indicate a point in a program where more than one


direction of flow may occur after processing operation. The occurrence
of flow of two or more paths is called branching and decision block
specify which of the paths will be taken once processing activity is
complete at each stage where decision has to be made.

GUIDELINES FOR DRAWING A FLOWCHART


a) There should be only one entry/ starting point and one exit point
of the program algorithm.
b) Use standard flow chart symbols
c) The logical flow should be clearly shown using arrows.
d) Use connectors to reduce the number of flow lines.
e) Use notes if necessary but don’t overcrowd the diagram.
f) Lines should be ideally vertical or horizontal.

Advantages of flow chart


- provide a visual aid to the program.
- Easier to understand because they are summarized and use
standard symbols.
- One is able to distinguish symbols.
- They slow a sequence of procedures.
- Are a good communication aid both to programmer and the
users.
- They form part of system documentation.

20
Start

Read n

n > 0

Sum = 0
Count = 0

Count<0

Read
number

Sum =sum + number


Count = count + 1

Average = sum +1

Write average

stop

21
2. Pseudocode
A pseudocode is a structured expression of an algorithm. It consists
of English like statement describing an algorithm. Indentation is used
to increase clarity.

Example
A pseudocode to computer average of n numbers

Begin
Read n
If (n>0)
Sum =0
Count =0
If (count < n) then
Read number
Sum = sum + number
Count = count + 1
End if
End if
Average = sum /n
Write average
End.

STRUCTURED PROGRAMMING /DESIGN

Structured programming /design entails developing a program as a


series of independent sections for the purpose of performing only one
task. Some of its facilities if—then –else, repeat—until, while –do
and for—do statements.

TYPES /METHODS OF STRUCTURED PROGRAM /DESIGNS

1. Top down approach (decomposition)


In a top -down design (decomposition), the macrostructure of the main
program is written first, and then the lower and lower subprograms are
written in stepwise modular form.
main program

Subprogram
Subprogram

Subprogram Subprogram Subprogram Subprogram 22


Top-down program development creates a high –level logic complex
structure and all the important program or system, interfaces first
before a great of detail code has been written. It is used mostly in
new systems. Coupling the various sub-programs is easy. It saves time
wasting and helps to avoid costly problems of interfacing.

Bottom – up design (decomposition)


In this method lower sub-programs are tested and debugged as shown
below.

Subprogram Subprogram Subprogram Subprogram

Subprogram
Subprogram

main program

The bottom –up tends to run into interface problems especially when
you have to put together subprograms or systems modules written by
different teams of programmers.

There are three problems uncounted in this approach.


a) They tend to involve more changes to existing code hence the
error is carried on to another part of the problem.
b) In bottom-up approach, interface problems are found after most
of the task have been done.

This method is used mostly to add new routines to existing programs or


systems.

c) Modularity (modular design)


Under this method, the program is broken up in more manageable units.
Each unit represents a major uniquely identifiable component of a
program called a module.
Each of these module can be written separately, almost independent of
all others, but on a co-ordinated basis. This approach facilities the
detecting errors (debugging) and maintenance of programs. It also
enables a large program to be developed in a shorter time by a team of
programmers thus, making workload lighter.

NB The purpose of a module is to aid in reducing the complexity of a


program.

Example

23
Computer pay

Income Deduction Tax calculation


calculation calculation (Module 3)
(Module 1) (Module 2)
d) Monolithic
This is an unformarised approach to program development. It is a total
program development approach where all subprograms are planned
together as a logical application. It is conventional approach, which
is unsystematic in nature

Structured coding programming


This method involves writing program instructions (codes) which
perform a certain distint task as a unit separates from other program
instructions. Each group of codes are in a modular form in units
called sub-programs, sub routines, procedures or functions. This
method make debugging easy , fast and changes in the codes independent
of other part of the program.

e) Jackson’s Structured Programming (JSP)


This method has an orderly and integrated collection of various
methods, tools and nations with it.

Block of diagrams are used to represent the structure of the programs


and how the modules relate to each other e.g.

Program

Initializ Initializ Initializ


e e e

Initia Initiali Initiali Initiali Initiali


lize ze ze ze ze

Object oriented programming

24
In this method, programs are designed around objects. Data is declared
as part of the code. The code then performs operations on data. In
this method data and code suddenly become one. It is data driven and
it is based on data types and their interactions.

NB: Criteria for selecting a design method

- readability
- reliability
- portability
- maintainability
- performance efficiency
- ease of use

*******

PROGRAMMING STYLES
Programming style refers to a set of rules or guidelines used when
writing the source code for a computer program.
Following a particular programming style will help programmers to
quickly read and understand the source code as well as helping to
avoid making errors during program development or modification.

Examples of programming styles

1. Use of case (lowercase or uppercase)


use of lowercase or uppercase both make a program easier to read and
understand. E.g. UnitPrice, TotalArea. TOTAL, square.

2. choice of identifiers
The identifiers chosen should be easy to read , understand and relate
to the of the program. For example using identifier Length to
represent longer side of a rectangle, UnitPrice to represent price per
unit of a commodity.

3. Indenting
This involves arranging program segments in a manner they can be
easily identified and their function interpreted. For example
subprogram with control structures should be written in a manner that
each loop is clearly identified.
e.g. if (x>0) then
if (x<100)
write(x) ;

4. use of subprogram

25
Subprograms are independent program segment within a program which
perform a specific task. Their use makes the program clear i.e. easy
to read and understand, easy to modify and debug etc.

5. Comments
They help to understand the program by the user, in various stages of
program flow by explaining /highlighting what a program does.

Properties of a good program


- Should perform all desired actions.
- Should be reliable
- Should be clear
- Should be easy to modify
- Should be implemented within a specific schedule and budget.

C programming

26

You might also like