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

Introduction To Program Com113

Introduction to Program
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Introduction To Program Com113

Introduction to Program
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 68

COURSE MATERIAL

For
INTRODUCTION TO PROGRAMMING

COM113

NATIONAL DIPLOMA
YEAR 1 SEMESTER 1

Week 1-13

1
WEEK 1
SPECIFIC LEARNING OUTCOMES
To understand:
Concept of programming
Features of a good program
Systems development cycle.

2
CONCEPT OF PROGRAMMING
A program is a set of instructions that tells the computer what to do. Computer programming (often
shortened to programming or coding), is the process of writing, testing, debugging/troubleshooting and
maintaining act of instructions (source code) for solving a problem with the computer. A source code is
written in an acceptable computer programming language. The code may be a modification of an
existing source or something completely new.
The purpose of programming is to create a program that exhibits a certain described behavior
(customization). The process of writing source code requires expertise in many different subjects,
including knowledge of the application domain. Alternatively, Programming is the craft of transforming
requirements into something that a computer can execute. Problem solving on computer is a task of
expressing the solution to the problem in terms of simple concepts, operations and computer code
(program) to obtain the results. To achieve this aim, you may proceed as follows:
1) First, understand the problem clearly:- Decide what you want to be calculated by the computer.
What will be the input data required? (If any). This is the problem formulation.
2) Write the steps of computation that are necessary to arrive at the solution. This is setting up the
algorithm.
3) Prepare a flowchart corresponding to the algorithm.
4) Develop the computer program. Test and run it on the computer.
There is an ongoing debate on the extent to which the writing of programs is an art, a craft or an
engineering discipline. Good programming is generally considered to be the measured application art,
craft and engineering, with the goal of producing an efficient and maintainable software (program)
solution. The discipline differs from many other technical professions in that programmers generally do
not need to be licensed or pass any standardized (or governmentally regulated) certification tests in order
to call themselves “programmers” or even “software engineers”.
FEATURES OF A GOOD COMPUTER PROGRAM
1) Accuracy: Any developed system has a purpose for which it is developed. A developed program
is a failure if it cannot meet the objectives for which it is proposed and designed. A good
program must performs the intended functions without errors.
2) Legibility: This involved writing code in a clear and understandable manner, making it easier for
others (or oneself) to read and maintain,
3) Understandability: The program codes will be easy for a programmer to read and understand
the logic involved in the programming.

3
4) Maintainability: A good program design will always be easy to change or modify when the
need arises. Programs should be written with the maintenance activity in mind. The structure,
coding and documentation of the program should allow another programmer to understand the
logic of the program and to make a change in one part of a program without unknowingly
introducing an error in another part of the same program.
5) Efficiency: The amount of system resources a program consumes (processor time, memory
space, slow devices, network bandwidth and to some extent even user interaction), the less the
better.
6) Reliability: Any developed program for a particular application can be depended upon to do
what it is supposed to accomplish. How often the results of a program are correct. This depends
on prevention of resulting from data conversion and prevention of errors resulting from buffer
overflows, underflows and zero division.
7) Generality: The program should be general within reasonable limits. Placing fixed values into
the program is not good programming practice. The program developed for a particular task, and
then it should also be used for all same purpose. For example, if a program is developed for a
particular organization, then it should suit all other similar organizations.
STAGES IN PROGRAM DEVELOPMENT
In other to produce a good program as previously described, the following steps in the order indicated
should be followed. Attempt to "save time" by skipping either of the steps or changing the order usually
end up costing more time and production of a faulty and inefficient program.
1. Problem definition and analysis
The programming problem should be studied carefully in order to understand what it is all about, it's
functions and requirements. In particular, the information (output) required, and the (input) data
supplied, if any. The study of all system design materials produced by the system analyst should be
carried out. Such materials include record layout charts, printer spacing charts and the program
specifications.
2. Providing method of solution
This step requires that you find necessary processing methods required to obtain the expected result
(output) from the given (input) data. You may have more than one way of solving a problem. This step
requires that you select the "best method". For example, to compute roots of a quadratic equation of the
form ax² + bx + c =0; you may use
Graphical method
i. Method of completing square

4
ii. The so-called "Almighty-formula".
iii. The “Almighty - Formula" is more amenable to computer solutions.

3. General Program design (program structure design)


The next step is to provide a generalized program design using - the "top-down", modular
approach. In this approach, the program is broken up into smaller pieces called modules, each of which
carries out one well-defined function. The procedure in this approach is started by identifying one
module that describes the overall function of the program. Then we proceed to partition this overall
function into its main components. Each of these components is in turn further subdivided into smaller
modules. This process is carried out until no module needs be sub-divided into smaller unit. Chapter 11
elaborates on this.
4. Detail program design
Having produced a general blue-print for the program as discussed in (3) above the next step in
program development is to design the detailed logic of each module. This can be accomplished using
structured flowcharts or pseudo-code. More on this in chapters five through ten.
5. Program desk-checking
The pseudo code for each module should be properly desk-checked to locate and correct as many
errors as possible before program module coding. By desk-checking we mean getting a piece of raw data
and manually tracing the program logic as it is written as it you were the machine executing the program
instructions.
6. Program Module Coding
The pseudo code of each module can now be coded properly in a suitable programming language (e.g.
COBOL, BASIC) employing the structured programming approach. The top-down approach can also be
applied to the coding. This means that higher level modules are coded first before the lower level
module. Each module should be properly documented stating its function (within the source program).
7. Program Testing
Test data, satisfying all possible conditions in the program should be assembled, expected output
prepared. The program should now be tested with the data collected. If a complied language (such as
COBOL, FORTRAN, etc) is used, compilation of the program will first precede this step. If only 9 out
of 10 conditions are tested for during program testing: the program testing will not be 100% reliable!
8. Program Documentation

5
After the program has been tested and completely debugged the structure chart, detailed
flowchart program descriptions or pseudo-code, of the logic and coding, test data, test runs with test
output and source listings etc. should be assembled and saved for future maintenance purposes.
ARITHMETIC OPERATORS
The following are used for arithmetic operations.
SYMBOL EXAMPLE MEANING
+ A+B Addition
- A-B Subtraction
* A*B Multiplication
/ A/B Division
= A=B A equals B
> A>B A greater than B
< A<B A less than B
>= A>=B A greater than or equal to B
<= A<=B A less than or equal to B
= A<>B A not equal to B

6
WEEK 2
SPECIFIC LEARNING OUTCOMES
To understand:
The Concept of Algorithm
Definition of Algorithm
Features of an Algorithm
Methods of representing Algorithm

7
CONCEPT OF ALGORITHM
Algorithm is a step-by-step procedure which is used to solve a problem. Computer needs precise and
well-defined instructions for finding solution of problems. If there is any ambiguity, the computer will
not yield the right results. It is essential that all the stages of solution of a given problem be specified in
details, correctly and clearly moreover, the steps must also be organized rightly so that a unique solution
is obtained.
Algorithm is a well-defined computational procedure, which takes some value (or set of values) as input
and produces some value, or a set of values, as output.

A typical programming task can be divided into two phases:


(a) Problem solving phase
In this stage an ordered sequence of steps that describe solution of the problem is produced.
Their sequence of steps can be called anti-Algorithm.
(b) Implementation Phase
In this phase, the program is implemented in some programming languages.
Algorithm may be set up for any type of problems, mathematical/scientific or business. Normally
algorithms for mathematical and scientific problems involve mathematical formulars. Algorithms for
business problems are generally descriptive and have little use of formula.
FEATURES OF AN ALGORITHM
1) Precise/Unambiguous: Each step must specify exactly what action is to be taken. No room for
vagueness or assumption e.g “Please assist me” is vague!
2) Finite: There must be a point within the algorithm in which work is required i.e an algorithm must
be able to terminate. For example, the algorithm below does not terminate.
1. Set E =0
2. Do while true
3. Set E = E=+2
4. Print E
5. Enddo
6. Stop
8
3) Effective: No instruction may be impossible to carry out by the person or machine executing the
algorithm. For example, to find the exact value of the square root of 2 is an impossible task and
therefore, it is not effective, because the square root of 2 is 1.4142135623.... Again, the instruction
"Go to hell" is precise but not effective.
4) Furthermore, algorithm usually starts with instructions to accept input which are to be processed
and must produce one or more output (i.e result of processing the inputs).
Example 1: Preparation of Eba (A local food)
1. Light the stove/gas cooker
2. Place a clean cooking pot on the stove
3. Put a desired quantity of water in the cooking pot
4. Test if the water is boiling. If yes, go to step 5 otherwise repeat step 4 until the water is boiling.
5. Pour Gari into the pot.
6. Stir until the desired texture is obtained
7. Stop
Example 2: Evaluation of Y =a (b-c)2 +d +2
1. Obtain the values of a,b,c and d in succession.
2. Subtract c from b giving R1.
3. Square R1 giving R2
4. Multiply R2 by a giving R3
5. Divide R3 by d giving R4
6. Add 2 and R4 together giving Y
7. Output or print Y
8. Stop
Note:
i. All the above steps are required
ii. Step 6 cannot come before step 5
Note that the main memory of the computer system is divided into a number of locations. Each location
has a unique address number by identified, and each location can be used to store data or instruction.
Variable names such as a,b,c etc are symbolic names of specific memory location in which data (the
values of a,b,c etc) are stored. These symbolic names are easier to remember than the numeric address
given to the memory locations.
The instruction in step 2 (i.e subtract c from b giving R1 i.e. R1 = b-c) actually causes the computer to
fetch (take) the content of memory location c, subtract it from the content of memory location b and

9
stores the result into memory location R1. The old value of location R1 is destroyed but those of c and b
remain intact.
METHODS OF REPRESENTING ALGORITHM
Algorithms are statements of steps involved in solving a particular problem. The steps to the solutions
are broken into series of logical steps in English related form. Programs are written to solve real life
problems. There can‟t be a solution if there is no recognized problem and once a problem exist, one
must take certain step in order to get a desired solution. The following methods could be used to
represent an algorithm.
 Methods of English Language
 Methods of Flowchart
 Methods of Pseudo code
 Methods of Decision table
 Methods of Data flow Diagram (DFD)
Pseudo Code
A pseudo code is the English-like representation of the program logic. It does not make use of standard
symbols like the flowchart. It is a sequential step by step arrangement of the instructions to be performed
to accomplish a task. It is an informal and artificial language that helps programmers develops
algorithms.
Structured programming is a universally accepted method of producing good program codes with
the properties of being.
- Less error prone
- Easy to read and understand
- Easy to debug
- Easy to maintain
Example 1
Write a pseudo code to find the area of a room.
Solution:
 Begin process
 Input room length
 Input room breadth
 Multiply length by breadth to get area
 Print area
 End process

10
Example 2
Write a Pseudo code for finding the greatest of 3 numbers represented as A, B, and C.
Solution:
 Begin process
 Input A,B,C
 If A>B then big = A
 Else big = B
 If big >C then biggest = big
Else biggest = C
Example 3
Write an Algorithm to determine a student‟s final grade and indicate whether it is passing or failing.
The final grade is calculated as the average of four marks.
Solution:
 Start
 Input a set of 4 marks
 Calculate their average by summing and dividing by 4.
 If average is below 50
Print “Fail”
else
Print “Pass”
Pseudo code
 Step 1: Input M1, M2, M3, M4
 Step 2: Grade ← (M1 + M2 + M3 + M4)/4
 Step 3: If (Grade < 50) then
 Print “FALL”
else
 Print “Pass”
 End it.
Example 4
Write an Algorithm to compute and output the average of 3 numbers a,b and c.
Step 1: Start
Step 2: Input a,b,c
Step 3: Compute Sum = a+b+c

11
Step 4: Compute Average = Sum/3
Step 5: Output Sum, Average
Step 6: Stop
Pseudo code
1. Input a,b,c
2. Calculate sum = a + b + c
3. Calculate Average = sum/3
4. Output sum, Average
5. Stop
Example 5:
Write algorithm to compute and print the circumference of a circle
The required steps are:
Step 1: Start
Step 2: Input Radius
Step 3: let pi = 3.142
Step 4: area = pi *r*r
Step 5: Circum = 2 * pi * r
Step 6: Print area, circum
Step 7: Stop

12
WEEK 3
SPECIFIC LEARNING OUTCOMES
To understand:
The Concept of Algorithm
Definition of Algorithm
Features of an Algorithm
Methods of representing Algorithm

13
English Language
The English form of representing algorithm entails breaking down the solution steps of the problem into
single and sequential English words. The steps are represented in English to say what action should be
taken in such a step.
Example 1
Develop an algorithm to obtain a book on computer from your school library located on the fourth floor
of the building. You are to proceed to the library from your ground floor classroom.
1. Start from the classroom
2. Climb the stairs to the 4th floor and reach the library
3. Search a book on computer
4. Have the book issued
5. Return to your classroom
6. Stop.
Note: The above algorithm solution of example 1, has been written in simple and clear English way.
Example 2
Develop an algorithm to find the average of four numbers stored in variables A,B,C,D
Solution
1. Start
2. Read values in variables A,B,C,D
3. Calculate the average as (A+B+C+D)/4 and store the result in P.
4. Write the value stored in P
5. Stop.
Example 3
Develop and algorithm to find the average of four numbers stored in variables A, B, C, D. When the
value of variable A is zero, no averaging is to be done.
Solution
1. Start
2. Read values stored in variable A,B,C.D
3. If the value of A is Zero, then jump to step 6
4. Calculate the average of A, B, C, D and store the result in variable P.
5. Write the value of P
6. Stop.

14
Flowchart
Flowchart is a representation of the algorithm using standard symbols. Each symbols has a new
function. The Algorithm steps determine which symbol to use to represent it in the flow each step
is linked to another step by using the directional arrows.

Flow Chart Symbols and Flow Chart For Mailing Letter

15
Decision table
A decision table is a form of truth table that structures the logic of a problem into simple YES
and No form. It is easily adapted to the needs of business data processing. It is a rectangle
divided into four sections called quadrants. It provides a structure for showing logical
relationships between conditions that exist and actions to be taken as a result of these conditions.
The condition entries

i Y is an indication that the condition is present

ii N is an indication that the condition is not present

iii - or blank is an indication that the condition was not tested.

The action entries

i X is an indication that the listed action to be taken.

ii Blank is an indication that the action is not to be taken.

Example 1: Decision table found in a printer Manual

Condition 1 2 3 4 5 6 7 8

Printer doesn‟t print Y Y Y N Y N N N

A red light is flashing Y Y N Y N Y N N

Printer is unrecognized Y N Y Y N N Y N

Action

Check the power cable X

Check the USB cable X X

Ensure driver software installed X X X X

Check/replace ink cartridge X X X X

Check for the paper jam X X

Example 2: A mobile service provider will allow a person to be a subscriber to their network

16
provided if the following conditions are met:
 They must have a bank or building society account
 They must have lived at the same address for at least a year
 They must be a home owner

Condition 1 2 3 4 5 6 7 8

Has a bank/building society account Y Y Y N Y N N N

Lived at the same address for>1yr Y Y N Y N Y N N

Is a home owner Y N Y Y N N Y N

Action

Can Subscribe X

Cannot Subscribe X X X X X X X

1) The number of condition is used to determine the number of entries by using the
formula, where n is the number of condition.
 Condition stub:- This gives a list of all the conditions that are relevant to the system.

 Condition entry: - Shows a YES or NO entry (abbreviated to Y for YES and N


for NO) whether listed condition is present or absent.
 Action stubs: - This quadrant gives a list of all the actions that could be taken by
the system, based on the conditions.

 Action entry: - This quadrant indicates whether a specific action will be taken or will not
be taken

Advantages of Decision Tables

1) They are simple, practicable and economical .All that is regarded to developed a decision
table is a piece of paper and a pencil

2) It makes the system designer to express the logic of the problem in direct and concise terms,
which results in the development of an effective and efficient program.

3) It is useful in program documentation i.e decision tables provide a quick and easily
understood over view of the system.
17
4) It is an excellent communication device to breach the gap between the computer personnel
who are responsible for developing the system and the non data processing personnel who
use the output of the system.

5) Decision tables are easy to update.

6) It is easy to learn how to use decision table.

7) The complexity and the amount of detail that can be handed by a decision table is un-
limited.

Disadvantages

1 Total sequence: The total sequence of an operation is not clearly shown in the
decision table i.e no overall picture is given as with flowcharts.
2 Logic: Where the logic of a system is simple flowcharts always serve the
purpose better.

ASSIGNMENT
Example 1: A website having the registration functionality and the vital information needed
include name, email, & address to register.
Use data flow diagram to show the three requirement that the registration depend on.

Data flow Diagrams


A data flow diagram shows the flow of the data among a set of components. The components
may be tasks, software components, or even abstractions of the functionality that will be
included in the software system. The actors are not included in the data flow diagrams. The
sequence of actions can often be inferred from the sequence of activity boxes.
Rules and Interpretations for correct data flow diagrams.
Creating data flow diagrams requires some guidelines and rules that should be followed. These
guidelines make DFD easily understandable and lucid.
Here are some of the key rules and tips.
1) Each process has at least one outgoing data flow and at least one ingoing data flow.
2) Each process can go to any other symbol (other processes, data store, and entities).
3) Each data store should have at least one incoming and at least one outgoing data flow.
4) Entities must be connected to a process by a data flow.
5) Data flows cannot cross with each other.
18
6) Data stores cannot be connected to external entities. Otherwise, it means you‟re allowing an
external entity access to your data files and stores.
7) The labels of processes can be verb phrases. Data stores are displayed by nouns.
8) Data flows cannot run between two external entities without going through a process (as you will
see in the data flow diagram examples below).
Examples Of Data Flow Diagram

19
WEEK 4
SPECIFIC LEARNING OUTCOMES
To understand:
Definition of flowchart

Description of flowchart symbols

Solving simple programming table with flowcharts

20
FLOWCHART
A flowchart is a pictorial representation of an Algorithm or of the plan of solution of a problem. It
indicates the process of solution, the relevant operations and computations, point of decision and other
information that are part of the solution. Flowcharts are of particular importance for documenting a
program. Special geometrical symbols are used to construct flowcharts. Each symbol represents an
activity. The activity could be input/out of data, computation/processing of data, taking a decision,
terminating the solution, etc. The symbols are joined by arrows to obtain a complete flowchart.
FLOWCHART SYMBOLS

General Rules for flowcharting


1) All boxes of the flowchart are connected with Arrows. (Not lines)
2) Flowchart symbols have an entry point on the top of the symbol with no other entry points. The
exit point for all flowchart symbols is on the bottom except for the Decision symbol.
3) The Decision symbol has two exit points; these can be on the sides or the bottom and one side.
21
4) Generally a flowchart will flow from top to bottom. However, an upward flow can be shown as
long as it does not exceed 3 symbols.
5) Connectors are used to connect breaks in the flowchart. Examples are:
 From one page to another page.
 From the bottom of the page to the top of the same page.
 An upward flow of more then 3 symbols
6) Subroutines and Interrupt programs have their own and independent flowcharts.
7) All flow charts start with a Terminal or Predefined Process (for interrupt programs or
subroutines) symbol.
8) All flowcharts end with a terminal or a contentious loop. Flowcharting uses symbols that have
been in use for a number of years to represent the type of operations and/or processes being
performed. The standardized format provides a common method for people to visualize.
Designing Algorithm with flowchart
In drawing a flowchart that represents the algorithm for a given programming problem, we must
always indicate the starting point at which the algorithm begins. This is always the first thing to specify.
Thus every flowchart begins with the symbol to indicate that the process of execution of the algorithm
has commenced.

START

Following this, step in the pseudo code representation have corresponding flowchart symbol to
represent it dramatically. For example the step;
1. Output a,b will be represented dramatically as:

Input a,b

Sımilarly, the step: calculate a = b- c will be represented in flowchart as.

calculate A = b- c

The arrow symbol ( ) is used to connect 2 flowchart symbols together to indicate that the two
operation follow each other in sequence. For example assume the following 3 operations follow each
other in sequence:

22
2 input a,b
3 calculate c = a +b
4 output c
The flowchart represent of the 3 operations will be

Output a,b
2. Input a,b.........................................

Calculate C=a+b
3. Calculate c = a + b……………………

Output C
4. Output c ………………………………

More real life programming example are now given to illustrate design of algorithm using flowchart.

Example 1
Draw a flowchart to find the average of four numbers stored in variables A,B,C,D.
Solution

Start

Read numbers in
A,B,C,D

Calculate the Average


P=(A+B+C+D)/4

Write the value of P

Stop

23
Example 2
A flowchart to find greater number between two numbers

Example 3
Write an algorithm and draw a flowchart that will read the two sides of a rectangle and calculate its area.
Solution
Pseudo code
 Begin process
 Input the Width(w) and Length(L) of a rectangle

 Calculate the area (A) by multiplying L with W


 Print A.

Algorithm
Step 1: Start
Step 1: Input W, L
Step 2: A← L * W
Step 3: Print A.

24
Flowchart

Stop

Input W,L

A←L*W

Print A

Stop

Example 4
Flow chart to print a message if x is greater than 5 or less than 5

Start

Input x

Yes No
x>5

“Msg”- Oh! That is too


“Msg”- Wow! This is great
small

Output msg

Stop

25
Example 5
Write a pseudo code with flow chart to find the area of two squares and add them.
Pseudo code
Step 1: Start
Side A A + B Side B
Start
Side A Side B
Step 2: Input side A
Step 3: Input side B
Input side A
Step 4: calculate Area A = side A * side A Input side b
Step 5: calculate Area B = side B * side B
Step 6: calculate total = Area A + Area B
Calculate Area A = side A * side A
Step 7: Print total
Calculate Area B = side B * side B
Step 8: stop
Calculate total = Area A + Area B

Print total

Stop
Uses of flowcharts

1 It gives us an opportunity to see the entire system as a whole.

2 It makes us to examine all possible logical outcomes in any process.

3 It provides a tool for communicating i.e a flowchart helps to explain the system to others.

4 To provide insight into alternative solutions.

5 It allows us to see what will happen if we change the values of the variable in the system
ADVANTAGES OF USING FLOWCHART

1. Communication flowcharts are visual aids for communicating the logic of a


system to all concerned.
2. Documentation: flowcharts are a means of documentation because:

3 The analyst/ programmers may leave the arrangement or they may forget the logic of the program.

4 Changes to the procedure are more easily catered for (modification).

5 Flowchart can be understood by new staff coming to the company

6 Analysis: flowcharts help to clarify the logic of a system i.e the overall picture of the
26
organization can be seen.

7 Consistency: A flowchart is a consistent system of recording. It brightens @ the


relationships between different parts of a system.

DISADVANTAGES OF USING FLOWCHART


1. Complex logic :- Where the logic of a problem is complex, the flowchart quickly becomes
clustered and lacks clarity.
2. Alterations:- If alterations are required the flowchart may require redrawing completely.

3. Reproduction:- As the flowchart symbols cannot be typed, reproduction of flowchart is


often a problem.

27
WEEK 5
SPECIFIC LEARNING OUTCOMES
To understand:
Design algorithm for problems involving.
Strictly sequence control structure
Selection control structure
Iteration control structure

28
DESIGNING ALGORITHM FOR COMMON PROGRAMMING LOGIC STRUCTURES
Sequence Control Structure
Implicitly, by default, the normal order of executing program statements is sequential. That is,
statements are executed one after the other in the sequence they physically appear in the program.
Sequence control structure represents a processing steps to be executed by the computer one after
the other in sequence of the order they are written. This control structure is illustrated below:

Step 1

Step 2

Step - n

Sequence Control Structure


Note:
1. Before using computer to solve a problem you must know the detail step involved. You must be
able to solve the problem manually, without the use of computer.
2. GGYou must know the sequence/order of carrying out the steps involved. For example, in the
evaluation of (3.14 + (6 * (0.5 of 25))) there are 3 main arithmetic operations involved (one
addition, one multiplication and one „of‟ operation (multiplication)). The correct evaluation of
the above expression will have to follow the rule of algebra symbolically coded as „BODMAS‟.
By this rule the above expression would be evaluated as:

3.14 + 6 * 0.5 of 2.5

The operation in the inner most parenthesis will be carried out first.
These steps can be arithmetic operation, assignment operation, subprogram call statement etc. example
above shows that Step1 will be carried out before steps 2, steps 2 before step3 and so on. Examples of
specific statements of actions or commands to be carried out sequentially are:
 Add 1 to A
 Print Result

29
 Assign A to B
 Input values of A, B, and C.
Example
Write an algorithm to compute and output the average of 3 numbers a,b, and c. Before the required
information (i.e Average) can be calculated, the values of a, b and c must be given (input) to the
computer. After the calculation, the average' must be explicitly output to the user. Thus the required
steps in sequence are:
1. Input a,b,c.
2. Compute Sum = a+b+c
3. Compute Average = Sum/3
4. Output Sum, Average
5. Stop
Example
Write algorithm to compute and print the circumference of a circle with diameter d.
The required steps are:
1. Input d
2. Calculate circumference = 3.142*d
3. Output circumference
4. Stop

ALGORITHMS AND PSEUDO-CODES – SELECTION STRUCTURE


Most real life, non - trivial programs require that a set of statements in an algorithm or program
be executed selectively or repeatedly based on the truth or otherwise of a specified condition, This
section treats the algorithm for program involving selection control structure.
SELECTION STRUCTURE
The selection control structure is one that involves decision-making in which one of two or more
sets of activities would have to be carried out depending on the truth or falsity of a given condition.
There are 3 main forms of this structure: single selection, binary selection and multiple/multiway
selection.
In single selection, a decision in made about the execution of one or more statements based on
the validity or otherwise of a specified condition. In binary selection, a choice is made between two (2)
alternative set of action based on the truth or otherwise of given condition(s) while in multiple selection,
there are usually more than two(2) actions from which to make a choice. Binary selection is the focus of

30
our discussion on selection structure. The structure of a binary selection is diagrammatically depicted as
shown below:

False True
?

False True
Action Action

Binary selection control structure


Binary selection involves a decision being made between two choices, splitting the program down
different paths. This decision is made based on a condition being either true or false. In Pseudocode
there are four keywords used for binary selection which include IF, THEN, ELSE and ENDIF.
 IF: Placed before the condition.
 THEN: What happens when the condition is true.
 ELSE: What happens if the condition is false.
 ENDIF: Closes the subprogram
THE IF-THEN-ELSE-ENDIF CONSTRUCT
The IF-THEN-ELSE- ENDIF construct is used to depict program segment involving selection
control structure. The construct is of the form:
IF (Condition) THEN
Statement - 1
Statement - 2
,,
,,
Statement - n
ELSE
Statement - n+1
Statement- n+2
,,
,,
Statement - n+m
ENDIF
31
If the condition is true, all statement -1 to statement -n will be executed sequentially; at the end;
control passes to the first statement following the ENDIF. That is, statement –n+1 to statement -n+m are
skipped. However, if the condition is not true control jumps over statement -1 to statement-n and
executes all instructions between the ELSE and the ENDIF, after which control passes to the statement
immediately following the ENDIF.
Example 1: Basic: Calculator
A program is to be developed that allows a user to enter in two different numbers. The software is to add
or subtract the numbers at the users discretion and display the result.
BEGIN Basic Calculator
BEGIN
Get Number 1
Get Number 2 Get number 1
IF Addition = TRUE
THEN Calculation = Number1 + Number2 Get number 2

ELSE Calculation = Number1 - Number2


ENDIF
No Addition Yes
Display Calculation = True?

END Basic Calculator Calculation Number1- Calculation Number1


Number 2 +Number 2

Display calculation

End

Example 2: use a structured (pseudo-code) algorithm to compute and print a salesman's commission
giving that commission is 10% of sales provided sales > 50.00; otherwise, no commission is given.
Solution
1. Input sales
2. If sales < 50
2.1 comm = 0.0
3. Else
3.1 comm = (10/100) * sales
4. ENDIF

32
5. Print sales, comm
6. Stop.
Example 3
Below is a pseudo-code to accept 2 values x and y and output the greater of the number.
1. Input X,Y
2. if X >Y
2.1 PRINT X
3. ELSE
3.2 PRINT Y
4. ENDIF
5. STOP
Example 4
Below is a pseudo-code of a program to compute and display the profit or loss made by a
business man who bought Q units of certain goods at #C per unit and sold it at #S per unit.
1. Input Q, C, S
2. Calculate cost price =Q*C
3. Calculate selling Price = Q *S
4. Calculate Profit loss = Selling Price – Cost Price
5. If Profit-loss > 0
5.1 Print "Profit =", Profit-loss
6. ELSE
6.1 Calculate loss = Profit -loss * (-1)
6.2 Print "Loss =", Loss
7. ENDIF
8. STOP

MULTIWAY/MULTIPLE SELECTION
Multiway selection allows a user to select from more than two options. In Pseudocode, the
keywords used for multiway selection include CASEWHERE, OTHERWISE and ENDCASE.
 CASEWHERE: Placed before the listing of conditions
 OTHERWISE: What to do if none of the set conditions are met
 ENDCASE: Concludes the case selection
After the use of the CASEWHERE statement, the next line is indented with each potential case on a new
line.
33
Pseudocode Example: Basic Calculator
A program is to be developed that allows a user two enter in two different numbers. The software is to
either add, subtract, multiply or divide the numbers at the users discretion. Result is to be displayed to
the user.
BEGIN Basic Calculator
Get Number l
Get Number2
CASEWHERE Calculation
Subtraction (-) : Numberl - Number2
Multiplication (*) : Numberl * Number2
Division (/) : Numberl / Number2
OTHERWISE : Numberl + Number2
ENDCASE
Display Calculation
END Basic Calculator

BEGIN

Get number 1

Get number 2

Calculation
=

Multiplication Division Otherw


Subtraction
ise

Number1-Number 2 Number1*Number 2 Number1/Number 2 Number1+Number 2

Display Calculation

End

34
WEEK 6
SPECIFIC LEARNING OUTCOMES
To understand:
Design algorithm for problems involving.
Strictly sequence control structure
Selection control structure
Iteration control structure

35
Iteration Logic (Repetitive flow)
The repetition structure can also be called a loop. In a loop, an operation or a set of
operation is repeated until some condition is satisfied. The basic form of repetition is termed DO
WHILE in the literature of structured programming. In some languages, the repetition structure
might be termed PERFORM UNTIL. In the perform until pattern, the program logic tests a
condition; if it is true, the program executes the operation and loops back for another test. If the
condition is true, the repetition ceases, is normally depicted by the diagram below

yes
Condition
true Yes - action
?

No
ITERATION CONTROL STRUCTURE
The iteration control structure in this (pre-test) iteration structure, the condition is first tested
before any execution of the action-block (called loop body). If the condition is true, the action block will
be carried out, followed by another testing of the condition. The loop or structure is terminated once the
specified condition is no longer valid. This control structure is generally denoted by a DO-WHILE-
ENDDO construct. It is of the form:
DO WHILE (Condition)
statement -1
statement -2


statement n
ENDDO
Statement -1 to statement-n will be repeatedly carried out until the condition is no longer true.
Usually the condition is first tested before executing statement -1 to statement -n. Furthermore one of
the statement between the DO WHILE and ENDDO Will be meant to alter the condition specified, thus
providing the means of terminating the algorithm.

36
Example 1: Write an algorithm for a program to calculate and print out the perimeter of ten rectangles
with given length and breadth.
Solution:
The steps required for processing one rectangle will be repeated 10 times for the above problem.
To solve this problem, a counting variable, say counter, will first be set to zero i.e Counter = 0. This is
because the necessary steps for one rectangle have not been carried out at all. The algorithm for
calculating the perimeter of one rectangle is given by:
1. Input l, b
2. Calculate perimeter = 2(1+ b)
3. Output perimeter
The 3 steps above are required for calculating the perimeter of the rectangle. These 3 steps will
have to be repeated 10 times to solve the given problem.
To indicate that one rectangle has been processed, the counting variable will have to be
incremented by 1; i.e Counter = Counter + 1.
This step (incrementing the counter by 1) will be part of the operation or processing required for one
rectangle. That is, the following 4 steps will be required:
1. Input l,b
2. Calculate perimeter =2 (L+b)
3. Output perimeter
4. Increment Counter by 1 (i.e Counter = Counter 1)
these 4 steps will have to be repeated as long as the value of the counting variable is less than 10 (i.e the
required number of rectangle to be processed). That is, the 4 steps will be repeated as long as Counter <
10. These 4 steps will now have to be enclosed within the DO- WHILE ENDDO structure. That is;
DO WHILE (Counter < 10)
1. Input l, b.
2. Calculate perimeter = 2 (l+ b)
3. Output perimeter
4. Counter = Counter +1
ENDDO
Thus the complete algorithm for the given problem is:
1. Set Counter =0
2. Do while (Counter < 10)
2.1 Input l,b

37
2.2 Calculate perimeter 2(l+b)
2.3 Output perimeter
2.4 Counter = counter + 1
3. Enddo
4. Stop
To repeat the same operation for 1000 rectangles, is a trivial matter. All that is required is to change the
terminating condition (Counter < 10) to (Counter < 1000).
Example is too specific to a particular number of rectangle This is why it has to be modified
when the operation is required for 1000 rectangles. If only 5 rectangles are to be processed, it will have
to be modified again. A more generalistic program for this problem that will not require frequent
amendment will be to develop an algorithm to process n rectangles, where n > 0.
Example 2
Write algorithm for a program to calculate and output the perimeter of n (n > o) rectangles. With given l
and b.
Solution: To do this we must first know the value of n. we obtain this through the keyboard. After
obtaining the value of n, the algorithm below will do the job, excepting that the terminating condition
will now have to be changed to (Counter < n). Thus the algorithm for the problem is:
1. Input N
2. Counter = 0
3. Do while (Counter < n)
3.1 Input l,b
3.2 Calculate perimeter = 2 (1 + b)
3.3 Output perimeter
3.4 Counter = Counter + 1
4. Enddo
5. Stop
Similarly, the pseudo-code for computing and printing the area of 3 triangles given the base b
and height h is as shown below.
Example 3:
1. Let I = 0
2. Do While (I < 3)
2.1 Read b,h
2.2 compute Area A = 1/2b*h

38
2.3 output b,h, Area
2.4 I=i+l
3. Enddo
4. Stop
There are various variations of the iteration control structures. This control structure is
implemented in different ways in different programming languages.
Note:
i. Steps 2.1, 2.2 and 2.3 are repeated until I is no longer less than 3
ii. Step 2.3 in the algorithm says = i +1. This is, a common statement in many Computer programs.
The meaning or semantics of the statement is that the new value of I equals the old value plus 2.
Similarly, a statement like P= P*Q means that the new value of P equals the old value of P
multiplied by Current value of Q.
iii. The counting variable is called the loop controlling variable. Its value is being altered by step
2.3, thus providing the means of terminating the loop.
Quiz: What will be the result if step 2.3 is not made part of the loop?
Note: Recollect that to carry out similar operation on 1000 triangles only requires changing the
terminating condition of example three in step 2 from Do while (i<3) to Do while (i<1000).
Example 3: can be modified to calculate and output the areas of triangles, m> 0. as given in the
algorithm below.
Example 4
Algorithm to calculate and output areas of m different triangles.
1. Input m (asking for number of triangles)
2. i= o
3. Do while (i < m)
3.1 Read b,h
3.2 Calculate Area = ½ * b*h
3.3 Output Area
3.4 i=i+1
4. Enddo
5. Stop

39
Example 5: Algorithm to input and display 100 names is:
1. K=0
2. Do while (K< 100)
2.1 Input name$
2.2 Output Name$
2.3 K=K+ 1
3. Enddo
4. Stop
Note: Example 5: can be modified to input and display n names as given below:
Example 6: Algorithm to input and display n names.
1. Input n (The statement asks for value of n)
2. K=0
3. Do while (K <n)
2.1 Input Name$
2.2 Output Name$
2.3 K = k+1
4. Enddo
5. Stop
Example 7: Algorithm to input and display given names until a name is "stop".
1. Input name$
2. Do while (name$ = “stop)
2.1 Output names$
3.1 Input name$
4. Enddo
5. Stop
Note:- This is an example of repetitive operation to be carried out until a given condition is satisfied. No
specific number of times for its repetition is given. However the terminating condition is when
names="stop".
This algorithm can be modified to display the number of names processed.
Example 8
Algorithm that display, input names until a given name is "stop". It displays the number of names
processed).
1. K= 0 (Variable counting number of names processed)

40
2. Input Name$
3. Do while (Name$ "stop")
3.1 Output Name$
3.2 K =k+l
3.3 Input name$
4. Enddo
5. Output "No of names processed =", K.
6. Stop

For example let us take 10 sets of numbers each set containing three. The problem is to get the
biggest number in each set and print it.
Algorithm

Step 1: Read the total number of sets

Step 2: Initialize the number of the set as N=1

Step 3: Read three numbers of a set say A, B, C.

Step 4: Compare A with 3 and choose the bigger.


Step 5: Compare the bigger number with C and Choose the biggest
Step 6: Print the biggest number,
Step 7: Increment the number of the set by 1 (N=N+1)
Step 8: Check whether we have exceeded 10. If not Go – To step 3. Otherwise.
Step 9: STOP

41
WEEK 7
SPECIFIC LEARNING OUTCOMES
To understand:
Identify the problem and confirm it solvable.

Design algorithm for the chosen method of solution with flowcharts or pseudo codes.

Code the algorithm by using a suitable programming language.

Test run the program on the computer.

42
HOW DO YOU WRITE AN ALGORITHM IN PYTHON?
Algorithms written in Python or any other language are most commonly written in a step-by-step
manner that clearly defines the instructions a program needs to run.
Though there is no defined standard as to how you should write algorithm, there are basic shared code
constructs between languages that we often use to create an algorithm, such as loops and control flow.
Algorithms are written to solve problems and overcome challenges in development, so ensuring that a
problem is well defined is key to writing a solution. Oftentimes, there may be multiple solutions to a
given problem and many algorithms may be implemented at once as a way of helping the program find
the best solution available.
However the solution is implemented, an algorithm should contain six characteristics.
HOW TO WRITE A PYTHON ALGORITHM: 6 CHARACTERISTICS

1. It is unambiguous and has clear steps.


2. The algorithm has zero or more well-defined inputs.
3. It must have one or more defined outputs.
4. The algorithm must terminate after a finite number of steps.
5. It must be feasible and exist using available resources.
6. The algorithm should be written independently of all programming code.

Example 1: Write a program to print the average of two numbers


num1 = int(input("Enter the number2: "))
num2 = int(input("Enter the number1: "))
average = (num1 + num2) / 2
print("The average of given number are:", average)

Example 2: A program that find the average of the sum number


list1 = [10,20,30,40]
sum_of_element = sum(list1)
len_of_list1 = len(list1)
average = sum_of_element/len_of_list1
print ("average of given numbers in list is:", average)

43
Example3: A program to output student grade
Marks = int(input("Please enter the marks:"))
grade=""
if(marks>=80):
grade="A Grade"
elif (marks>=60):
grade="B Grade"
elif (marks>=50):
grade="C Grade"
elif (marks>=45):
grade="D Grade"
else:
grade="fail"
print("Marks:", marks)
print("Grade:",grade)

Example 4: A program to compute two input


num1 = (input("Enter the first number: "))
num2 = (input("Enter the second number: "))
# Compare the numbers and print the greater one
if num1 > num2:
print(f"{num1} is greater than {num2}")
elif num2 > num1:
print(f"{num2} is greater than {num1}")
else:
print("Both numbers are equal")
Example 5: A python program to print number from 1 to 50
# Using a count variable to print numbers from 1 to 50
count = 1
while count <= 50:
print(count)
count += 1

44
Example 6: A python program to find the area of triangle

#Input the base and height of the triangle from the user
base = float(input("Enter the base of the triangle: "))
height = float(input("Enter the height of the triangle: "))
#Calculate the area of the triangle
area = 0.5 * base * height
#Print the area of the triangle
print(f"The area of the triangle with base {base} and height {height} is: {area}")

45
WEEK 8 & 9
SPECIFIC LEARNING OUTCOMES
To understand:
Explain modular programming concept.

Explain top-down design technique.

Illustrate program design with program structure charts, hierarchical Network,


Hierarchical.

46
THE CONCEPT OF MODULAR PROGRAMMING
As program become larger, and more complex, it becomes more difficult to write clear
understandable solutions that work correctly. The goal of modular programming is to break up
the program into small parts that are more easily understood. The planning, coding and testing
can be done on these small, relatively simple units, rather than on one large, complex body of
code.
MODULAR PROGRAMMING

One popular technique in designing program structure is called modular programming This is the
process by which a large called program modules A program module is a well-defined program
programming tasks can be sub-divided into smaller parts or functions segment which performs a specific
task For e.g. if a program is meant reasonable to have separate modules to handle each of the main to do
matrix addition, subtraction, multiplication and inversion, it is operation viz: addition, subtraction,
multiplication and inversion

1) At a higher a level, a module can be a subprogram which can be separately compiled and tested.

2) At the lower level it can be an "open" subroutine such as macro, se functions. internal
procedures, function, etc

A subprogram is a small self-contained sequence of instruction (program) for accomplishing a


well-defined task. This task is usually a component of another main task. Unlike a program, a
subprogram cannot be directly executed on its own without the help of another program or subprogram
which will act as a calling program.

A subroutine is a subprogram. A subprogram that can be separately complied independent of


its calling program unit is called an "external" or "closed" subroutine, while a subprogram that
can only be complied along and within its calling program unit is called an "internal or "open"
subprogram.
ADVANTAGES OF MODULAR PROGRAMMING
i. A program can concentrate on a particular function.
ii. Each program segment can easily be corrected. If any error exists.
iii. A team of programmer can be working simultaneously on different specific tasks that
constitute the entire program. As a result, a complex program can be completed in a
shorter time.

47
BASIC PROGRAM STRUCTURE CHART
A structure chart is a diagram in which program modules are represented by rectangular r boxes and the
inter module relationship by means of connecting lines.
There are 2 basic forms of program structure. These are hierarchical and network.
Hierarchical Program Structure
In this structure, there is a single module at the top with one more subordinate modules. The singular top
module is superior to its subordinate modules, however, these subordinates may themselves have
additional subordinate modules to which they are superior. Any given module can be subordinate to only
one superior, but may be superior to one or more subordinate modules. The figure below illustrate this
structure.

Level 0 A

Level 1 B C

E F A
Level 2 D

Representation of Hierarchical Structure


There are 2 characteristics of a strict hierarchical structure.
a. There is a single superior module for the entire hierarchy.
b. There is only one superior module for each subordinate module.
Below represents a typical program structure for program to list from disk to printer.
MAIN

1. OPEN FILES PROCESS CLOSE FILE


2. PRINT REORDS

READ READ WRITE


ROUTINE ROUTINE OUTPUT
Program structure of a list - from-disk- to-printer program.

48
Example 1: Draw a hierarchical structured chart for a program to input 2 numbers x and y and output
the result when any of the four basic arithmetic is carried out on them.

Arithmetic
Operations

Input Data PROCESS Output Result

?
1 2 3 4

Addition Subtraction Multiplication Division

Hierarchical structured chart for a simple Arithmetic operation

NETWORK PROGRAM STRUCTURE


There is no single module that is superior to all others, and inter-module relationship are
unrestricted. That is, 2 modules may relate to each other in both directions. The fiqure below illustrates
this.
A
A

B C
B C

D
D E
Representation of Network Structure
One clear mark of program complexity is obviously the number of modules in a program.
However, the greater source of complexity the number of inter-module relationships. Such relationship
indicated by the network structure in tends to undo the benefits derived from modularization by making
functional distinctions between program modules less clear. Thus resulting in program structure that are
complex, difficult to understand and difficult to modify. As a result of all these, hierarchical, rather than
network structures are the preferred form of program structures.

49
TOP DOWN DESIGN APPROACH
The process by which well-partitioned modular program can be structured into hierarchies is
called top-down design.
In top-down design, we begin by identifying one module that describes the overall functions of
the program., Then we proceed to partition this overall function into its main components. For e.g
suppose that the overall function is "process student result". The main components are House-keeping-
and-heading. process-routine, print-class-average and print-summary-lines.

PROCESS RESULT

HOUSE KEEPING PROCESS PRINT CLASS PRINT


& HEADING ROUTINE AVERAGE SUMMARY LINES

Top-down modular design with two levels


We then review these functions and determine whether the breakdown is complete and/ or
whether it contains redundancies. For instance, we might question whether or not the 2 modules print-
class-average and print- summary-lines are really different functions, and if not whether they could be
replaced by a single module that could be called print-last-lines.
When we are satisfied with the modules comprising the 2 level in the structure chart, we repeat
the process, considering each of these modules in turn as if it were the top module. That is, for each
main sub function of the overall task, we identify specific sub functions which comprise that function.
For e.g. we ask what are the main functions which can be developed for house-keeping and heading? As
shown below, two sub-functions can be identified: open-files-and-initialıze-variable and print-headings.

PROCESS RESULT

HOUSE KEEPING PROCESS PRINT CLASS


& HEADING ROUTINE AVERAGE

OPEN FILES & PRINTING


INITIALIZE VARIABLE HEADINGS

Top-down modular design with 3 levels


The general process of identifying sub-functions continues with each lower level in turn. We
stop when no function at any level can be partitioned any further, given that each function is a cohesive

50
task that ultimately can be expressed in one cohesive module. A cohesive module is one that performs
only one function and all program statements in the module are directly related to that function only.
Top-down design is a well- tested and effective method of developing good program designs. A
complete design for the program is as shown below.
Note:
The curve arrow from process-result module to process-routine is used to indicate a looping situation. It
represents repetitive invocation of process-routine by process-result.

PROCESS RESULT 1

HOUSE KEEPING PROCESS PRINT CLASS


& HEADING AVERAGE 2
ROUTINE

OPEN FILES & PRINTING PRINTING PROCESS


INITIALIZE HEADINGS HEADINGS
RECORD 3
VARIABLE A1
B2

COMPUTE GRADES FORMAT & PRINT ACCUMULATE TOTAL


FOR EACH COURSE
AND REMARK B21 DETAIL B22
B23
4

Design of Result Processing Program


GUIDELINES FOR MAKING PROGRAM STRUCTURE CHARTS
1. There should be one module for only one well-defined function.
2. Give a unique number (or unique name) to each module. If a module appears more than once in
a structure chart (i.e if it is called by more than one module), assign it the same number
everywhere it is called.
3. Develop modules that are functionally cohesive, which means that each statement in the module
directly contributes to carrying out the single function of the module.
4. Develop modules that are low in coupling: that is, try to minimize the number of data items
which are accessed by 2 or more program modules.
5. A module should require no more than 50 lines of coding.
6. Modules should call only those module which are below their own level.

51
WEEK 10 & 11
SPECIFIC LEARNING OUTCOMES
To understand:
Explain machine language, low-level language and High level languages

Various programming languages

Differentiate between programming languages

52
LEVELS OF COMPUTER PROGRAMMING LANGUAGES
The generally accepted dictionary definition of language is that it is a "notational system for
communication". A programming Language is thus a notational system for communicating with the
computer. That is, a programming language is a means by which users is express what they want
computer to do for them. Examples of programming language are BASIC, FORTRAN, COBOL, PL/1,
C, JAVA etc.

Programming language can be categorized into 3 main levels: machine language, low-level language
and high-level language. Each category or level of programming language has its own distinguishing
features, advantages and disadvantages.

MACHINE LANGUAGE

Machine Code or machine language is a low-level programming language that can be understood
directly by a computer‟s central processing unit (CPU). Machine code consists of sequences of
binary numbers, or bits, which are usually represented by 1s and 0s, and which form the basic
instructions that guide the operation of a computer. The specific set of instructions that
constitutes a machine code depends on the make and model of the computer‟s CPU. For instance,
the machine code for the Motorola 68000 microprocessor differs from that used in the Intel
Pentium microprocessor.
Writing programs in machine code is tedious and time-consuming since the programmer must
keep track of each specific bit in an instruction. Another difficulty with programming directly in
machine code is that errors are very hard to detect because the program is represented by rows
and columns of 1s and 0s.
Features of Machine Language
The main feature or characteristic of machine language is that it is machine dependent or machine -
oriented. This means that each computer system has its own unique machine language and it is different
nt from any other machine language of another system This difference is due to the fact that different
machines have different word length. instruction sets and instruction formats. This is analogous to
human language like Yoruba, which has different dialects For example, we have the Igbomina, Ekiti,.
ljesa, etc All these are Yoruba languages but are different significantly from one another.
Advantages of Machine Language
1) Less code is produced
2) Storage is saved
3) User has direct control of machine instruction
4) Execution is faster as no translation is needed
5) The programmer knows all the registers and instruction that use them.

53
Disadvantages of Machine Language

1) Cumbersome ie, tedious and difficult to learn

2) Programmer‟s fluency is affected, thereby making the programs developed inefficient.

3) The developed programs are error prone and difficult to debug (correct)

4) Programs written to be run on one computer machine cannot be run on another type of computer.
This is because each family of computer has its own unique ML which is tailor- made to its
individual hardware features.

HIGH LEVEL LANGUAGE


High-Level Language is a computer language that provides a certain level of abstraction from the
underlying machine language through the use of declarations, control statements, and other
syntactical structures. In practice, the term comprises every computer language above assembly
language. The next generation of language is called the 3rd generation. The computer
programmers enjoy using this language because it gives them the fluency, the flexibility and the
opportunity to express their thought to the best of their ability. The languages of this generation
are called High level language. The high level languages are referred to as machine language and
assembly language.
Types of High-level Language
There are different categories of high-level language
i. Scientific language e.g FORTRAN, BASIC, ALGOL.
ii. Commercial language e.g COBOL
iii. Multipurpose language (that is, a language suitable for both scientific and business application)
e.g PL/1
iv. System programming e.g JOVIAL, BLISS, C,B,EL, ETC.
v. Artificial intelligence e.g LISP, PROLOG.
vi. Database application e.g Dbase IV, FoxBASE, Oracle, etc
Features of High Level Languages
i. They are machine-independent, unlike their predecessors,
ii. A Single high- level language instruction corresponds too many machine code-instructions.
iii. They need to be translated before they can be understood the machine.
Advantages of High Level Language

1) It makes programming easier for the human being.


2) High level instructions are easier to understand and faster to code.
54
3) Error correction and resting of program is easier
4) They are machine independent. That is, program written for computer can be transferred
to another computer with little or no modification.
Disadvantages of High Level Languages

1) High level language tends to be inefficient in the use of CPU and other facilities.

2) Machine code instructions are produced and then requires more storage spaces.

3) More time is required to run the program as it has to be translated.

LOW LEVEL LANGUAGE


Low-level languages are machine dependent languages in which symbolic code form example, MUL A
is used instead of numeric machine code (e.g 000101-000001001) to represent instructions in the
computer. There is one-to-one correspondence between each symbolic code instruction and its
corresponding machine code form. That is, every low-level language statement has exactly one and only
one machine language equivalent. An example of low-level la: Jage is assembly language. Every
computer has its own Assembly Language.
For e.g, the AL equivalent of the program segment to add 2 valıses A and B, storing the results in C is:
LDA A Load the content of memory location A into the accumulator
ADD B Add the content of memory location B to the accumulator and leave the result in the
accumulator
STA C Store the content of accumulator into memory location C.

Features of Low-Level Language


i. Symbolic (mnemonics) codes are used in place of machine codes.
ii. Symbolic address is frequently used instead of the actual machine address. For example ADD B.
iii. It needs to be translated to machine language before it can be understood by the computer
iv. It is largely machine dependent, like machine languages.
Advantages of Low Level Language
1) Program translation is easier than high level language and machine language
2) It affords the programmer the opportunity to understand the internal structure
of the hardware and its registers.
Disadvantages of Low Level Language
1) It is machine dependent, That is, cannot be transferred to another computer.
2) Program development is slow as the programmer must have detailed knowledge of
the hardware structure.
55
3) Program maintenance is slow and error prone.

DISTINGUISH BETWEEN SYSTEM COMMANDS AND PROGRAM STATEMENTS


Program:
Program, as name suggest, are simply set of instructions developed by programmers in programming
languages that consist of compiled code and run directly from computers operating system.
Command: :
Command, as name suggests, are instruction given by user to computer to perform specific task and
are forwarded by command line from user to operating system and initiated from application program
as well as from user interface.

Program Command

Programs are collection of instructions Command are orders to computer program


understandable by CPU. to perform particular task.

Programs are instructions created by Commands are instruction given by user to


programmer or software developer. computer.

It is used to indicate that which operating CPU It is used to tell application or system to do
should execute on set of data. something or perform task.

Types of programs include word processors, Types of command includes input program
game programs, graphic programs, data base commands, utility commands, internal
systems, etc. command, external command, etc.

It comes in different forms i.e. special words


These are files stored in one of bin directories
that program understand, function keys,
like /bin, /user/bin, /user/local/bin.
buttons, etc.

Programs are handled by programmer who Commands are handled by part of operating
write compute programs. system i.e. command interpreter.

Computer without command is useless


Computer without programs is just considered
because there users give command to
as dump box because these programs make
computer to specific task and if there will be
computer active.
no user then computer is just a dump box.

56
WEEK 12
SPECIFIC LEARNING OUTCOMES
To understand:

Debugging.

Identify sources of bugs in a program


Explain syntax, run-time and logical errors.
Identify techniques of locating bugs in a program
Explain program maintenance.
Distinguish between debugging and maintaining a program
Advantages and disadvantages

57
THE CONCEPT OF DEBUGGING AND MAINTAINING PROGRAM
Debugging is the art of diagnosing errors in programs and determining how to correct them. "Bugs"
come in a variety of forms, including: coding errors, design errors, complex interactions, poor user
interface designs, and system failures. Learning how to debug a program effectively, then, requires that
you learn how to identify which sort of problem you're looking at, and apply the appropriate techniques
to eliminate the problem.

Bugs are found throughout the software lifecycle. The programmer may find an issue, a software tester
might identify a problem, or an end user might report an unexpected result. Part of debugging
effectively involves using the appropriate techniques to get necessary information from the different
sources of problem reports.

Debugging is described as identification and removal of localized implementation errors or bugs from a
program or system. Program debugging is often supported by a debug tool, a software tool that allows
the internal behavior of the program to be investigated in order to establish the existence of bugs. This
tool typically offer trace facilities and allow the planting of breakpoint in the program at which
execution is to be suspended so that examination of partial results is possible and permit examination
and modification of the values of program variables when a breakpoint is reached.

In computer program/software, a bug is an error in coding or logic that causes a program to malfunction
or to produce incorrect results. The computer software (debug tool) is used to detect, locate, and correct
logical or syntactical errors in a computer program. Similarly, in hardware, a bug is a recurring physical
problem that prevents a system or set of components from working together properly. To detect, locate,
and correct a malfunction or to fix an inoperable system, the term troubleshoot is more commonly used
in hardware contexts. The three major program error are; syntax error, logical error and run-time error.
SOURCES OF BUGS IN A PROGRAM
With coding errors, the source of the problem lies with the person who implements the code. Examples
of coding errors include:
 Calling the wrong function ("moveUp", instead of "moveDown")
 Using the wrong variable names in the wrong places ( "moveTo(y, x)" instead of "moveTo(x,
y)")
 Failing to initialize a variable ( "y = x + 1", where x has not been set)
 Skipping a check for an error return disk space, available processor speed, and overwhelming
input/output devices. More difficult design errors fall into several categories:

58
 Failure to hide complexity
 Incomplete or ambiguous "contracts"
 Undocumented side effects

Complex interactivity bugs arise in scenarios where multiple parts of a single program, multiple
programs, or multiple computers interact.
Software users readily see some design errors, while in other cases design flaws make a program more
difficult to improve or fix, and those flaws are not obvious to a user. Obvious design flaws are often
demonstrated by programs that run up against the limits of a computer, such as available memory,
available

Sometimes, computer hardware simply fails, and it usually does so in wildly unexpected ways.
Determining that the problem lies not with the software itself, but with the computer(s) on which it is
usually complicated by the fact that the person debugging the software may not have access to the
hardware that shows the problem.
PREVENTING BUGS
No discussion of debugging software would be complete without a discussion of how to prevent bugs in
the first place. No matter how well you write code, if you write the wrong code, it won't help anyone. If
you create the right code, but users cannot work the user interface, you might as well have not written
the code. In short, a good debugger should keep an open mind about where the problem might lie.

Although it is outside the scope of this discussion to describe the myriad techniques for avoiding bugs,
many of the techniques here are equally useful after the fact, when you have a bug and need to uncover
it and fix it. Thus, a brief discussion follows.
BASIC DEBUGGING TECHNIQUES/STEPS
Although each debugging experience is unique, certain general principles can be applied in debugging.
This section particularly addresses debugging software, although many of these principles can also be
applied to debugging hardware.
The basic steps in debugging are:
1. Recognize that a bug exists
2. Isolate the source of the bug
3. Identify the cause of the bug
4. Determine a fix for the bug
5. Apply the fix and test it
59
1. Recognize a bug exists

Detection of bugs can be done proactively or passively.


An experienced programmer often knows where errors are more likely to occur, based on
the complexity of sections of the program as well as possible data corruption. For example, any
data obtained from a user should be treated suspiciously. Great care should be taken to verify that
the format and content of the data are correct. Data obtained from transmissions should be
checked to make sure the entire message (data) was received. Complex data that must be parsed
and/or processed may contain unexpected combinations of values that were not anticipated, and
not handled correctly. By inserting checks for likely error symptoms, the program can detect
when data has been corrupted or not handled correctly.
If an error is severe enough to cause the program to terminate abnormally, the existence of
a bug becomes obvious. If the program detects a less serious problem, the bug can be recognized,
provided error and/or log messages are monitored. However, if the error is minor and only causes
the wrong results, it becomes much more difficult to detect that a bug exists; this is especially
true if it is difficult or impossible to verify the results of the program.
The goal of this step is to identify the symptoms of the bug. Observing the symptoms of the
problem, under what conditions the problem is detected, and what work-around, if any, have been
found, will greatly help the remaining steps to debugging the problem.

2. Isolate source of bug


This step is often the most difficult (and therefore rewarding) step in debugging. The idea is to
identify what portion of the system is causing the error. Unfortunately, the source of the problem
isn't always the same as the source of the symptoms. For example, if an input record is
corrupted, an error may not occur until the program is processing a different record, or
performing some action based on the erroneous information, which could happen long after the
record was read.
This step often involves iterative testing. The programmer might first verify that the input is
correct, next if it was read correctly, processed correctly, etc. For modular systems, this step can
be a little easier by checking the validity of data passed across interfaces between different
modules. If the input was correct, but the output was not, then the source of the error is within the
module. By iteratively testing inputs and outputs, the debugger can identify within a few lines of
code where the error is occurring.

60
3. Identify cause of bug
Having found the location of the bug, the next step is to determine the actual cause of the bug,
which might involve other sections of the program. For example, if it has been determined that
the program faults because a field is wrong, the next step is to identify why the field is wrong.
This is the actual source of the bug, although some would argue that the inability of a program to
handle bad data can be considered a bug as well.
A good understanding of the system is vital to successfully identifying the source of the
bug. A trained debugger can isolate where a problem originates, but only someone familiar with
the system can accurately identify the actual cause behind the error. In some cases it might be
external to the system: the input data was incorrect. In other cases it might be due to a logic error,
where correct data was handled incorrectly. Other possibilities include unexpected values, where
the initial assumptions were that a given field can have only "n" values, when in fact, it can have
more, as well as unexpected combinations of values in different fields (field x was only supposed
to have that value when field y was something different). Another possibility is incorrect
reference data, such as a lookup table containing incorrect values relative to the record that was
corrupted.
Having determined the cause of the bug, it is a good idea to examine similar sections of
the code to see if the same mistake is repeated elsewhere. If the error was clearly a typo, this is
less likely, but if the original programmer misunderstood the initial design and/or requirements,
the same or similar mistakes could have been made elsewhere.

4. Determine fix for bug


Having identified the source of the problem, the next task is to determine how the
problem can be fixed. An intimate knowledge of the existing system is essential for all but the
simplest of problems. This is because the fix will modify the existing behavior of the system,
which may produce unexpected results. Furthermore, fixing an existing bug can often either
create additional bugs, or expose other bugs that were already present in the program, but never
exposed because of the original bug. These problems are often caused by the program executing a
previously untested branch of code, or under previously untested conditions.

In some cases, a fix is simple and obvious. This is especially true for logic errors where the
original design was implemented incorrectly. On the other hand, if the problem uncovers a major
design flaw that permeates a large portion of the system, then the fix might range from difficult to
impossible, requiring a total rewrite of the application.

61
In some cases, it might be desirable to implement a "quick fix", followed by a more permanent
fix. This decision is often made by considering the severity, visibility, frequency, and side effects
of the problem, as well as the nature of the fix, and product schedules (e.g., are there more
pressing problems?).

5. Fix and test


After the fix has been applied, it is important to test the system and determine that the fix handles
the former problem correctly. Testing should be done for two purposes: (1) does the fix now
handle the original problem correctly, and (2) make sure the fix hasn't created any undesirable
side effects.
For large systems, it is a good idea to have regression tests, a series of test runs that exercise the
system. After significant changes and/or bug fixes, these tests can be repeated at any time to
verify that the system still executes as expected. As new features are added, additional tests can
be included in the test suite.
The diagram below illustrates the fix and test approach of debugging a program.

62
SYNTAX OF A PROGRAM
The syntax of a program is the rules defining the legal sequences of symbolic elements in a
particular language. The syntax rules define the form of various constructs in the language, but
say nothing about the meaning of these constructs. Examples of constructs are; expressions,
procedures and programs.
PROGRAMMING ERRORS
Error simply means mistake. That is errors occur in programs as a result of system failure
(hardware), wrong code/instructions (software) and human error. There are four categories of
programming error;
RUN-TIME ERRORS (EXECUTION ERROR)

Is an error that occurs during the execution of a program. In contrast, compile-time errors occur
while a program is being compiled. Runtime errors indicate bugs in the program or problems that
the designers had anticipated but could do nothing about. For example, running out of
memory will often cause a runtime error.
Note that runtime errors differ from bombs or crashes in that you can often recover gracefully
from a runtime error.
Run-time errors have the following basic characteristics;
 Program is compiled OK, but something goes wrong during execution e.g division
by zero or an attempt to read data that does not exist.
 Detected by the computer run-time system
 Computer usually prints error message and stops.
DEFINE LOGICAL ERRORS
A problem that causes a program to produce invalid output or to crash (lock up). The problem is
either insufficient logic or erroneous logic. For example, a program can crash if there are not
enough validity checks performed on the input or on the calculations themselves, and the
computer attempts to divide by zero. Bad instruction logic misdirects the computer to a place in
the program where an instruction does not exist, and it crashes.
A program with bad logic may produce bad output without crashing, which is the reason
extensive testing is required. For example, if the program is supposed to add an amount, but
subtracts it instead, bad output results, although the computer keeps running.
Logic errors have the following basic characteristics;

 Program compiles and executes OK but produces unexpected or incorrect results.

63
 Detected by programmer (i.e You!)
 Hardest to detect, locate and find.
DEFINE SYNTAX ERRORS (COMPILATION ERROR)
Syntax error is a programming error in which the grammatical rules of the language are broken.
That is program errors that occur due to violation or disobedience of rules of the programming
language. When syntax error occurs, the program execution is halt until the error or bug is
detected, located and corrected. Syntax errors can be detected by the compiler, unlike semantic
errors which do not become apparent until run-time.
Run-time errors have the following basic characteristics;
 Error in the form of statement: misspelled word, unmatched parenthesis, comma out of place
 Detected by the computer at compiler time
 Computer cannot correct error, so object program is not generated and thus program is not
executed
 Computer (compiler) prints error messages, but continues to compile.
Linker errors: These types of errors have the following basic characteristics;
 Prevents the generation of an executable image
 Common linker errors;
o specifying the wrong header file
o disagreement among the function prototype, function definition and calls to that function
The difference between run-time, logical and syntax errors?
 Students should identify the differences from the above explanations.
PROGRAM MAINTENANCE
Program/software maintenance is the modification of a software product after delivery to correct faults,
to improve performance or other attributes, or to adapt the product to a modified environment. This
international standard describes the 6 software maintenance processes as:
Categories of Program maintenance
E.B. Swanson initially identified three categories of maintenance: corrective, adaptive, and perfective.
1. The implementation processes contains software preparation and transition activities, such as the
conception and creation of the maintenance plan, the preparation for handling problems identified
during development, and the follow-up on product configuration management.

Preventive maintenance: Modification of a software product after delivery to detect and


correct latent faults in the software product before they become effective faults.
64
2. Adaptive maintenance: Modification of a software product performed after delivery to keep a
software product usable in a changed or changing environment.
3. Perfective maintenance: Modification of a software product after delivery to improve performance
or maintainability.
DIFFERENCE BETWEEN PROGRAM MAINTENANCE AND DEBUGGING
A common perception of maintenance is that it is merely fixing bugs. However, studies and surveys
over the years have indicated that the majority, over 80%, of the maintenance effort is used for non-
corrective actions. Key findings shows that program maintenance is really evolutionary developments
and that maintenance decisions are aided by understanding what happens to systems (and software) over
time. While Debugging is a very important task in the software development process, because an
erroneous program can have significant consequences for its users. Some languages are more prone to
some kinds of faults because their specification does not require compilers to perform as much checking
as other languages. Use of a static analysis tool can help detect some possible problems.

65
WEEK 13
SPECIFIC LEARNING OUTCOMES
To understand:
Employ structured approach to both flowcharting and program development.

THE CONCEPT OF GOOD PROGRAMMING PRACTICES


Structured Programming is a general term referring to programming that produces programs with
clean flow, clear design, and a degree of modularity or hierarchical structure. Benefits of
structured programming include ease of maintenance and ease of readability by other
programmers.
Structured Programming is one step beyond modular programming with guidelines for “good”
modules and “poor” modules. The structured programming guidelines also define “proper” flow
of control and coding standards (such as indentation). In many large programming projects where
statistics have been kept, it has been shown that structured programming has many demonstrable
advantages over the old style, unstructured programs, such as:
1. Programs are more reliable. Fewer bugs appear in testing and later operation.
2. Programs are easier to read and understand
3. Programs are easier to test and debug.
4. Programs are easier to maintain.
Most commercial programming shops report that at least 50 percent of programmer time is spent
making changes and correction in existing programs rather than developing new programs (some
report more than 90 percent maintenance). Anything that will save time in correction and
maintenance can save a company considerable money. It is easy to see why most commercial
stops hiring programmers insist on structured programming techniques.
The current definition of structured programming includes standards for program design, coding
and testing that are designed to create proper, reliable, and maintainable software. These
standards include coding guidelines and rules for flow of control and module formation.

Structured Coding Guidelines


The structured coding guidelines are designed to make programs more reliable and easier to understand.
1. Use meaningful variable names
2. Code only one statement per line.
3. Use Remarks to explain program logic.
4. Indent and align all statements in a loop.
5. Indent the THEN and ELSE actions of an IF statement.
66
GOOD PROGRAMMING PRACTICE
Good Programming Concept or Style makes code/program easier to maintain and modify.
Maintaining and modifying code is made much easier by following a few often-overlooked
techniques.

Whether the original programmer or someone else needs to make a change in the code the job is
much easier if the original programmer used lots of comments, gave the variables and constants
descriptive names, and sketched out the basic structure of the program at the very beginning in
pseudo-code.
Using Comments in Code
The use of comments can mean the difference between code which any competent programmer
can maintain or modify and a program that even the original programmer has trouble figuring out.
Every routine should start with at least one comment that documents the purpose of the routine
and any non- obvious dependencies or effects that the routine may have on other portions of the
program.

In a development environment in which several programmers will be contributing code, adding a


comment identifying the person who wrote the code will definitely help others to know who to
ask if a question should arise.
Using Descriptive Names for Variables, Constants and Functions
It can be very tempting to use short names for variables and constants but it is not a good
programming practice. A name such as DateOfBirth is much easier for other programmers to
understand than dob.
Global variable names can all start with a lower case "g" so that any programmer looking at the
code will instantly know which entities are local and which are global. Likewise, a lower case "k"
can be the first letter of constants. This type of self-documenting code greatly reduces the need
for comments and some typical errors.
Using Pseudo-code in Comments

When first developing the structure of a program it can be very helpful to write out the different
routines in pseudo-code. This is language which resembles a cross between English and the
programming language that the code will eventually be written in.

Using pseudo-code allows the programmer to concentrate on the conceptual aspects of the
program without being distracted by syntax rules. The pseudo-code can also be the basis of the

67
comments so it can server two purposes.
Using Modular Coding
Whenever possible, the lines of a routine should fit entirely on one screen of the editor. By
keeping routines short, it is easier to comprehend them and see errors. Having short routines also
forces the programmer to break each task into distinct sub-tasks, each of which is easier to
maintain and modify in the future.
Modular coding also has the advantage of creating reusable routines that can be used in
other programs. Once a routine is debugged and verified it is easier to copy and paste it into
another program than to write it all over again.
Following these simple suggestions will make a programmer's code easier to maintain and
modify. It may seem like more work, but in the end the net result is greater efficiency and fewer
mistakes.

68

You might also like