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

Introduction to Computer Science

The document is a comprehensive lecture note for an Introduction to Computer Science course prepared by Muhammad Aminu Ahmad for the 2017/2018 session. It covers various topics including computer systems, hardware and software, data representation, networks, applications of computers, ethics, and programming languages. Each section provides detailed insights into the evolution, components, and applications of computer science.

Uploaded by

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

Introduction to Computer Science

The document is a comprehensive lecture note for an Introduction to Computer Science course prepared by Muhammad Aminu Ahmad for the 2017/2018 session. It covers various topics including computer systems, hardware and software, data representation, networks, applications of computers, ethics, and programming languages. Each section provides detailed insights into the evolution, components, and applications of computer science.

Uploaded by

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

DEPARTMENT OF MATHEMATICAL SCIENCES

CSC101 LECTURE NOTE

2017/2018 SESSION
INTRODUCTION TO COMPUTER SCIENCE

Prepared By

Muhammad Aminu Ahmad

Copyright © 2018
All Rights Reserved
Contents

1 Computer Systems 1
1.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Development of Computers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2.1 The Abacus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2.2 Napier’s Bones . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2.3 Pascal’s Calculator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2.4 Leibniz Calculator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.2.5 Analytical Engine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.2.6 Tabulating Machine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.2.7 Electronic Digital Computer . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.3 Generations of Computer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.3.1 First Generation (1945-1956) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.3.2 Second Generation Computers (1956-1963) . . . . . . . . . . . . . . . . . . . . 9
1.3.3 Third Generation Computers (1964-1971) . . . . . . . . . . . . . . . . . . . . . 9
1.3.4 Fourth Generation (1971-1984) . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.3.5 Fifth Generation (1984-1990) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.3.6 Sixth Generation (1990 and beyond) . . . . . . . . . . . . . . . . . . . . . . . . 11
1.3.7 Emerging Generation (Quantum Computers) . . . . . . . . . . . . . . . . . . . 11
1.4 Classes of Computers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.5 Characteristics of Computers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.6 Components of a Computer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

2 Computer Hardware and Software 16


2.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.2 Computer Hardware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.2.1 Central Processing Unit (CPU) . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.2.2 Primary Storage Devices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
2.2.3 Secondary Storage Devices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.2.4 Input and Output Devices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.3 Computer Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.3.1 System Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.3.2 Middleware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28

ii
Kaduna State University CSC101 Lecture Note: 2017-2018 Session

2.3.3 Application Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28

3 Data Representation and Processing 30


3.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
3.2 Data Representation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
3.2.1 Representing Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.2.2 Representing Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.2.3 Representing Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
3.2.4 Representing Sounds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
3.3 Data Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
3.3.1 Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
3.3.2 Data Processing Activities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
3.3.3 The Data Processing Cycle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
3.3.4 Data Organisation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36

4 Networks 37
4.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
4.2 Computer Networks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
4.2.1 Network Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
4.2.2 Network Topology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
4.2.3 Communication Media . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
4.2.4 Network Devices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
4.2.5 Transmission Modes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
4.3 The Internet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
4.3.1 Internet Evolution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
4.3.2 Internet Layered Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
4.3.3 Internet Design Principles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
4.3.4 Internet Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52

5 Applications of Computers 56
5.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
5.2 Office Automation System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
5.3 Business . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
5.4 Banking and Finance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
5.5 Computational Science . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
5.6 Education . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
5.7 Engineering Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
5.8 Expert Systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
5.9 Geographic Information System (GIS) . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
5.10 Health . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
5.11 Defence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67

Muhammad Aminu Ahmad Page iii


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

6 Computer Ethics and Responsibility 70


6.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
6.2 Software Piracy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
6.3 Privacy of Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
6.4 Use of Computers and the Internet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
6.5 Green Computing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
6.6 Ethical Responsibilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73

7 Programs and Programming Languages 75


7.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
7.2 How Programs Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
7.3 Programming Languages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
7.3.1 Machine Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
7.3.2 Low-level Language/Assembly Language . . . . . . . . . . . . . . . . . . . . . 77
7.3.3 High level Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
7.3.4 Translation of High-Level Languages . . . . . . . . . . . . . . . . . . . . . . . 80

8 Problem Solving 82
8.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
8.2 Problem Solving Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
8.2.1 Understand and Define the Problem . . . . . . . . . . . . . . . . . . . . . . . . 82
8.2.2 Devise a Plan to Solve the Problem . . . . . . . . . . . . . . . . . . . . . . . . 83
8.2.3 Select the Best Way to Solve the Problem . . . . . . . . . . . . . . . . . . . . 85
8.2.4 Test and Evaluate the Solution . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
8.3 Algorithmic Problem Solving . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
8.3.1 Algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
8.4 Problem Solving Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
8.4.1 Sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
8.4.2 Selection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
8.4.3 Repetition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
8.4.4 Selection and Repetition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94

9 Python Essentials 97
9.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
9.2 Python Interpreter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
9.3 Variables and Expression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
9.4 Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
9.4.1 Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
9.4.2 Boolean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
9.4.3 String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
9.4.4 List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100

Muhammad Aminu Ahmad Page iv


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

9.4.5 Tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101


9.4.6 Indexing Sequences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
9.4.7 Slicing Sequences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
9.4.8 Concatenating and Repeating Sequences . . . . . . . . . . . . . . . . . . . . . . 103
9.4.9 Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
9.4.10 Type Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
9.4.11 Operator Precedence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
9.5 Executing Python Programs from File . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
9.6 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
9.7 Input and Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
9.7.1 Console Input and Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
9.7.2 Input and Output with Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
9.8 Programming Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
9.8.1 Example 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
9.8.2 Example 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
9.8.3 Example 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109

10 Python Control Structures 110


10.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
10.2 Conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
10.3 Looping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
10.3.1 For Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
10.3.2 While Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
10.3.3 Break and Continue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
10.4 Programming Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114

11 Python Functions and Modules 119


11.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
11.2 Using Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
11.3 Creating Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
11.4 Variable Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
11.5 Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121

Muhammad Aminu Ahmad Page v


Chapter
1
Computer Systems

1.1 Introduction
Computers have revolutionized the world within a short period of decades; computers have become
indispensable in every sphere of human life. In education, computers are used for tasks such as writing
papers, searching for articles, sending email and participating in online classes. At work, people use
computers to analyse data, make presentations, conduct business transactions, communicate with
customers and co-workers, control machines in manufacturing facilities, and do many other things.
At home, people use computers for tasks such as paying bills, online shopping, communicating with
friends and family and playing computer games. Computers can do a wide variety of things because
they can be programmed. This means that computers are not designed to do just one job, but to do
any job based on their programs.
A program is a set of instructions that a computer follows to perform a task. Programs are commonly
referred to as software. Software is essential to a computer because it controls the hardware components
of the computer and everything the computer does. The software and hardware that make computers
useful are created by individuals working as programmers/software developers and computer engineers
respectively. A programmer/software developer is a person with the training and skills necessary
to design, create, and test computer programs, while a computer engineer focuses on designing and
manufacturing computer hardware. Today, the work of computer programmers and engineers is obvious
in business, medicine, government, law enforcement, agriculture, academics, entertainment, industries,
communications and many other fields. Therefore a computer can be defined as follows:

A computer is a programmable machine, operating under the control of instructions stored


in its own memory. The computer is capable of accepting data (input), processing data
arithmetically and logically, producing output from the processing and storing the results
for future use. In other words, a computer is an electronic device that performs specified
sequences of operations as per the set of instructions (known as programs) given on a set of
data (input) to generate desired information (output) and store the result for future used.

1
Kaduna State University CSC101 Lecture Note: 2017-2018 Session

The “machine” part of the computer is called the hardware, while the “programmable” part is called
the software. Computers are used to fulfil general and specific needs of the public, industries and
governments. Computers use software to make it easier for users to accomplish some tasks and solve
problems. Therefore, software must be efficient, robust, easy to use, visually appealing and produce
correct results.
The field of computer science deals with processing information through computations and analysis
to solve a particular problem or produce a desired result, depending on the application at hand.
Using software for a desired task or to solve problems requires programming and domain knowledge.
Computer science is not an area of study that covers anything related to IT support, repairing
computers, installing and configuring networks, using application packages, browsing the web or
playing games. Computer science focuses on understanding what goes on behind software and how
software/programs can be made more efficiently. The general areas of discipline in computer science
are computer architecture, operating systems, programming languages and compilers, algorithms,
data structures and complexity, computability theory, numerical analysis, networking and distributed
computing, parallel computing, information management/database systems, software development (or
software engineering), human-computer communication/interaction, graphics and visual computing
and intelligent systems (or artificial intelligence). Thus, studying computer science requires specializing
in one or more of these areas.

1.2 Development of Computers


In early days, counting was something difficult and started by using stones. People followed a set
of procedure to perform calculation with these stones, which later led to the creation of the first
mechanical calculating device known as ABACUS.
1.2.1 The Abacus
Abacus is known to be the first mechanical calculating device that was used to perform addition and
subtraction easily and quickly. This device was first developed by the Egyptians in the 10th century
B.C, but it was given its final shape in the 12th century A.D. by the Chinese educationalists. Abacus
is made up of wooden frame in which rods where fitted across with round beads sliding on the rods as
shown in Figure 1.1. It is divided into two parts called ‘Heaven’ and ‘Earth’. Heaven was the upper
part and Earth was the lower one. Thus, any number can be represented by placing the beads at
proper place. Early merchants used the abacus to keep trading transactions. But as the use of paper
and pencil spread, the abacus lost its importance.

Muhammad Aminu Ahmad Page 2


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

Figure 1.1: The Abacus

1.2.2 Napier’s Bones


In 1617, John Napier of Scotland invented a calculating device called the Napier Bones. Napier’s bone
used bone rods for counting purpose, where some numbers were printed on these rods. Figure 1.2
shows the picture of Napier’s bones. These rods can be used for addition, subtraction, multiplication
and division.

Figure 1.2: The Napier’s Bones

1.2.3 Pascal’s Calculator


In 1642, Blaise Pascal, the 18-year-old son of a French tax collector, invented what he called a numerical
wheel calculator to help his father with his duties. Pascal’s calculator, also called a Pascaline, is a
brass rectangular box that used eight movable dials to add sums up to eight figures long. Figure 1.3
shows the Pascal’s calculator.

Figure 1.3: The Pascal’s calculator

For example, as one dial moved ten notches or one complete revolution, it moves the next dial,

Muhammad Aminu Ahmad Page 3


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

which represented the ten’s column - one place. When the ten’s dial moved one revolution, the dial
representing the hundred’s place moved one notch and so on. The drawback to the Pascaline was its
limitation to addition.
1.2.4 Leibniz Calculator
In 1694, a German mathematician and philosopher, Gottfried Wilhem von Leibniz, improved the
Pascaline by creating a machine that could also multiply. Like its predecessor, Leibniz’s mechanical
multiplier worked by a system of gears and dials. Partly by studying Pascal’s original notes and
drawings, Leibniz was able to refine his machine. Figure 1.4 shows the Leibniz calculator.

Figure 1.4: The Leibniz calculator

The centrepiece of the machine was its stepped-drum gear design, which offered an elongated version
of the simple flat gear. It was not until 1820 that mechanical calculators gained widespread use.
Charles Xavier Thomas de Colmar, a Frenchman, invented a machine that could perform the four basic
arithmetic functions. Colmar’s mechanical calculator, the Arithmometer, presented a more practical
approach to computing because it could add, subtract, multiply and divide. With its enhanced
versatility, the Arithmometer was widely used until the First World War. Figure 1.5 shows the
Arithmometer device.

Figure 1.5: The Arithmometer device

1.2.5 Analytical Engine


The real beginning of computers is with an English mathematics professor, Charles Babbage. Babbage
noticed a natural harmony between machines and mathematics; machines were best at performing
tasks repeatedly without mistake, while mathematics, particularly the production of mathematics

Muhammad Aminu Ahmad Page 4


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

tables, often required the simple repetition of steps. The problem centred on applying the ability of
machines to the needs of mathematics. Babbage’s first attempt at solving this problem was in 1822
when he proposed a machine to perform differential equations, called a Difference Engine. Figure 1.6
shows the Differential Engine.

Figure 1.6: The Differential Engine

Powered by steam and large as a locomotive, Difference Engine would have a stored program and
could perform calculations and print the results automatically. After working on the Difference Engine
for 10 years, Babbage was suddenly inspired to begin work on the first general-purpose computer,
which he called the Analytical Engine. Figure 1.7 shows the Analytical Engine.

Figure 1.7: The Analytical Engine

Babbage’s assistant, Augusta Ada King, was instrumental in the machine’s design. She helped
in revising plans, secured funding from the British government and communicated the specifics of
the Analytical Engine to the public. Ada’s understanding of the machine allowed her to create the
instruction routines to be fed into the computer, making her the first female computer programmer. In
the 1980’s, the U.S. Defense Department named a programming language ADA in her honour.
Babbage’s steam-powered engine, although ultimately never constructed, may seem primitive by
today’s standards. However, it outlined the basic elements of a modern general purpose computer and
was a breakthrough concept. Consisting of over 50,000 components, the basic design of the Analytical
Engine included input devices in the form of perforated cards containing operating instructions and a

Muhammad Aminu Ahmad Page 5


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

"store" for memory of 1,000 numbers of up to 50 decimal digits long. It also contained a "mill" with
a control unit that allowed processing instructions in any sequence and output devices to produce
printed results. Babbage borrowed the idea of punch cards to encode the machine’s instructions from
the Jacquard loom. The loom, produced in 1820 and named after its inventor, Joseph-Marie Jacquard,
used punched boards that controlled the patterns to be woven. For this great invention of the computer,
Sir Charles Babbage is also known as the father of computer.
1.2.6 Tabulating Machine
In 1889, an American inventor, Herman Hollerith, also applied the Jacquard loom concept to computing.
His first task was to find a faster way to compute the U.S. census. Unlike Babbage’s idea of using
perforated cards to instruct the machine, Hollerith’s method used cards to store data, which he fed
into a machine that compiled the results mechanically. Each punch on a card represented one number
and combinations of two punches represented one letter. Instead of ten years, census takers compiled
their results in just six weeks with Hollerith’s machine. Figure 1.8 shows the Tabulating Machine.

Figure 1.8: The Tabulating machine

In addition to their speed, the punch cards served as a storage method for data and they helped
reduce computational errors. Hollerith brought his punch card reader into the business world, founding
Tabulating Machine Company in 1896, later to become International Business Machines (IBM) in 1924
after a series of mergers. Other companies such as Remington Rand and Burroughs also manufactured
punch readers for business use. Both business and government used punch cards for data processing
until the 1960’s.
1.2.7 Electronic Digital Computer
Vannevar Bush developed a calculator for solving differential equations in 1931. The machine could
solve complex differential equations that had long left scientists and mathematicians baffled. The
machine was cumbersome because hundreds of gears and shafts were required to represent numbers
and their various relationships to each other. To eliminate this bulkiness, John Vincent Atanasoff, a
professor at Iowa State College (now called Iowa State University) and his graduate student, Clifford
Berry, envisioned an all-electronic computer that applied Boolean algebra to computer circuitry. This
approach was based on the mid-19th century work of George Boole who clarified the binary system of
algebra, which stated that any mathematical equations could be stated simply as either true or false.

Muhammad Aminu Ahmad Page 6


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

By extending this concept to electronic circuits in the form of on or off, Atanasoff and Berry developed
the first automatic electronic digital computer called Atanasoff-Berry Computer (ABC), which was
successfully tested in 1942. Figure 1.9 shows the Atanasoff-Berry Computer.

Figure 1.9: The Atanasoff-Berry Computer

1.3 Generations of Computer


In the year 1946, the first successful electronic computer called ENIAC was developed and it was the
starting point of the current generation of computers.
1.3.1 First Generation (1945-1956)
With the onset of World War II, governments sought to develop computers to exploit their potential
strategic importance. This increased funding for computer development projects hastened technical
progress. By 1941 German engineer Konrad Zuse had developed a computer, the Z3, to design airplanes
and missiles. The Allied forces, however, made greater strides in developing powerful computers.
In 1943, the British completed a secret code-breaking computer called Colossus to decode German
messages. The Colossus’s impact on the development of the computer industry was rather limited for
two important reasons. First, Colossus was not a general-purpose computer; it was only designed to
decode secret messages. Second, the existence of the machine was kept secret until decades after the
war.
American efforts produced a broader achievement. Howard H. Aiken, a Harvard engineer working
with IBM, succeeded in producing an electronic calculator by 1944. The purpose of the computer was
to create ballistic charts for the U.S. Navy. It was about half as long as a football field and contained
about 500 miles of wiring. The Harvard-IBM Automatic Sequence Controlled Calculator, or Mark I for
short, was an electronic relay computer. It used electromagnetic signals to move mechanical parts. The
machine was slow (taking 3-5 seconds per calculation) and inflexible (in that sequences of calculations
could not change); but it could perform basic arithmetic as well as more complex equations.
Another computer development spurred by the war was the Electronic Numerical Integrator and
Computer (ENIAC), produced by a partnership between the U.S. government and the University of
Pennsylvania. Consisting of 18,000 vacuum tubes, 70,000 resistors and 5 million soldered joints, the
computer was such a massive and consumed 160 kilowatts of electrical power. ENIAC was developed
by John Presper Eckert and John W. Mauchly, and unlike the Colossus and Mark I, the machine

Muhammad Aminu Ahmad Page 7


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

was a general-purpose computer that was 1,000 times faster than Mark I. In the mid-1940’s John von
Neumann joined the University of Pennsylvania team, initiating concepts in computer design that
remained central to computer engineering for 40 years. Figure 1.10 shows the ENIAC computer.

Figure 1.10: The ENIAC computer

Von Neumann designed the Electronic Discrete Variable Automatic Computer (EDVAC) in 1945
with a memory to hold both a stored program as well as data. This "stored memory" technique as
well as the "conditional control transfer" that allowed the computer to be stopped at any point and
then resumed, allowed for greater versatility in computer programming. The key element to the von
Neumann architecture was the central processing unit, which allowed all computer functions to be
coordinated through a single source. Figure 1.11 shows the ENIAC computer. In 1951, Remington Rand
built the Universal Automatic Computer I (UNIVAC I), which became one of the first commercially
available computers to take advantage of these advances.

Figure 1.11: The EDVAC computer

First generation computers were characterized by the fact that operating instructions were made-
to-order for the specific task for which the computer was to be used. Each computer had a different
binary-coded program called a machine language that told it how to operate. This made the computer

Muhammad Aminu Ahmad Page 8


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

difficult to program and limited its versatility and speed. Other distinctive features of first generation
computers were the use of vacuum tubes (responsible for their breathtaking size) and magnetic drums
for data storage.
1.3.2 Second Generation Computers (1956-1963)
By 1948, the invention of the transistor greatly changed the development of computers. The transistor
replaced the large, cumbersome vacuum tube in televisions, radios and computers, reduced the size
of electronic machinery. The transistor was at work in the computer by 1956. Coupled with early
advances in magnetic-core memory, transistors led to second generation computers that were smaller,
faster, more reliable and more energy-efficient than their predecessors. The first large-scale machines
to take advantage of this transistor technology were early supercomputers such as Stretch by IBM
and LARC by Sperry-Rand. These computers were both developed for atomic energy laboratories and
could handle an enormous amount of data, a capability much in demand by atomic scientists. The
machines were costly and tended to be too powerful for the business sector’s computing needs, thereby
limiting their attractiveness.
Second generation computers replaced machine language with assembly language, allowing abbrevi-
ated programming codes to replace long and difficult binary codes. Throughout the early 1960’s, there
were a number of commercially successful second generation computers used in business, universities
and government from companies such as Burroughs, Control Data, Honeywell, IBM, Sperry-Rand and
others. These second generation computers were also of solid state design and contained transistors
in place of vacuum tubes. They also contained all the components associated with the modern day
computer: printers, tape storage, disk storage, memory, operating systems, and stored programs. One
important example was the IBM 1401, which was universally accepted throughout industry, and is
considered by many to be the Model T of the computer industry.
By 1965, most large business routinely processed financial information using second generation
computers. It was the stored program and programming language that gave the computers the flexibility
to finally be cost effective and productive for business use. More sophisticated high-level languages such
as COBOL (Common Business-Oriented Language) and FORTRAN (Formula Translator) came into
use. These languages replaced cryptic binary machine code with words, sentences, and mathematical
formulas, making it much easier to program a computer. New types of careers such as programmer,
analyst and computer systems expert, and the entire software industry began with second generation
computers.
1.3.3 Third Generation Computers (1964-1971)
Despite the improvement provided by transistors over the vacuum tube, they still generated a great
deal of heat, which damaged sensitive internal parts of a computer. The quartz rock eliminated this
problem. Jack Kilby, an engineer with Texas Instruments, developed the integrated circuit (IC) in
1958. The IC combined three electronic components onto a small silicon disc, which was made from
quartz. Scientists later managed to fit even more components on a single chip, called a semiconductor.
As a result, computers became ever smaller as more components were squeezed onto the chip. Figure
1.12 shows a vacuum tube, a resistor and an integrated circuit.

Muhammad Aminu Ahmad Page 9


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

Figure 1.12: A vacuum tube, a resistor and an integrated circuit

Another third-generation development included the use of an operating system that allowed machines
to run many different programs at once with a central program that monitored and coordinated the
computer’s memory.
1.3.4 Fourth Generation (1971-1984)
After the integrated circuits, the only place to go was down in size, that is, Large Scale Integration
(LSI) could fit hundreds of components onto one chip. By the 1980’s, Very Large Scale Integration
(VLSI) squeezed hundreds of thousands of components onto a chip. Ultra-large Scale Integration
(ULSI) increased that number into the millions. It also increased their power, efficiency and reliability.
The Intel 4004 chip, developed in 1971, took the integrated circuit one step further by locating all
the components of a computer (central processing unit, memory, and input and output controls) on
a minuscule chip. Unlike the previous integrated circuit that must be manufactured to fit a special
purpose, now one microprocessor could be manufactured and then programmed to meet any number of
demands. Soon everyday household items such as microwave ovens, television sets and auto-mobiles
with electronic fuel injection incorporated microprocessors. Such condensed power allowed everyday
people to harness the power of computers. They were no longer developed exclusively for large business
or government contracts.
By the mid-1970’s, computer manufacturers sought to bring computers to general consumers. These
minicomputers came complete with user-friendly software packages that offered even non-technical users
with an array of applications, most popularly word processing and spreadsheet programs. Pioneers
in this field were Commodore, Radio Shack and Apple Computers. In the early 1980’s, arcade video
games such as PAC Man and home video game systems such as the Atari 2600 ignited consumer
interest for more sophisticated, programmable home computers. In 1981, IBM introduced its personal
computer (PC) for use in home, office and schools. The 1980’s saw an expansion in computer use in all
three arenas as clones of the IBM PC made the personal computer even more affordable. Computers
continued their trend toward a smaller size, working their way down from desktop to laptop and
palmtop computers. Apple’s Macintosh line, in direct competition with IBM’s PC, was introduced
in 1984. Notable for its user-friendly design, the Macintosh offered an operating system that allowed
users to move screen icons instead of typing instructions. Users controlled the screen cursor using a
mouse, a device that mimicked the movement of a hand on the computer screen.

Muhammad Aminu Ahmad Page 10


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

As computers became more widespread in the workplace, new ways to harness their potential
developed. As smaller computers became more powerful, they could be linked together or networked
to share memory space, software, information and communicate with each other. As opposed to a
mainframe computer which was one powerful computer that shared time with many terminals for many
applications, networked computers allowed individual computers to form electronic cooperation using
either direct wiring, called a Local Area Network (LAN) or telephone lines.
1.3.5 Fifth Generation (1984-1990)
This generation of computers introduced machines with hundreds of processors that could all be working
on different parts of a single program. The scale of integration in semiconductors enabled building
chips with a million components, and semiconductor memories became standard on all computers.
Many advances in the science of computer design and technology emerged such as parallel processing,
which replaces von Neumann’s single central processing unit design, with a system harnessing the
power of many processors to work as one. The superconductor technology, which allows the flow of
electricity with little or no resistance, greatly improved the speed of information flow. Computer
networks, both wide area network (WAN) and local area network (LAN) technology developed rapidly
and single-user workstations also became popular. The fifth generation computers also introduced
the use of Artificial intelligence. For example, expert systems assist doctors in making diagnoses by
applying the problem-solving steps a doctor might use in assessing a patient’s needs.
1.3.6 Sixth Generation (1990 and beyond)
Most of the developments in computer systems since 1990 were improvements over established systems.
This generation brought about gains in parallel computing in both the hardware and in improved
understanding of how to develop algorithms to exploit parallel architectures. Workstation technology
continued to improve, with processor designs now using a combination of RISC, pipelining, and parallel
processing. Wide area networks, network bandwidth and speed of operation and networking capabilities
have kept developing tremendously. Personal computers (PCs) now operate with Gigabit per second
processors, multi-Gigabyte disks, gigabytes of RAM, colour printers, high-resolution graphic monitors,
stereo sound cards and graphical user interfaces. Thousands of software (operating systems and
application software) are existing today. This generation also brought micro controller technology,
which are embedded inside some other devices (often consumer products) so that they can control
the features or actions of the product. They work as small computers inside devices and now serve as
essential components in most machines.
1.3.7 Emerging Generation (Quantum Computers)
Conventional digital computers store information using bits represented by 0s or 1s. Quantum
computers use quantum bits, or qubits, to encode information as 0s, 1s, or both at the same time. This
superposition of states and other quantum mechanical phenomena of entanglement and tunnelling
enables quantum computers to manipulate enormous combinations of states at once. A qubit can be
thought of like an imaginary sphere. Whereas a classical bit can be in two states - at either of the two
poles of the sphere - a qubit can be any point on the sphere. This means a computer using these bits

Muhammad Aminu Ahmad Page 11


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

can store a huge amount of information using less energy than a classical computer. D-Wave Systems
developed an integrated quantum computer system running on a 128-qubit processor in 2011. D-Wave
Systems launched the D-Wave two (512-qubit quantum computer) in 2013 and D-Wave 2X (1000-qubit
quantum computer) in 2015. In January 2017, D-Wave Systems launched the D-Wave 2000Q quantum
computer (2000 qubit). Figure 1.13 shows the D-Wave 2000Q quantum computer.

Figure 1.13: D-Wave 2000Q Quantum Computer

1.4 Classes of Computers


Computers can be classified by their mode of operations; analogue, digital and hybrid, and their sizes;
supercomputers, mainframes, minicomputers, workstations and microcomputers.
Analogue Computers
An analogue computer is designed to process continuous physical quantities. Examples of analogue
computer usage include monitoring temperature, voltage and current reading in a power station. Each
of these parameters can attain an infinite number of values, not just simple on and off. An analogue
computer has the following characteristics:
• It operates by measuring.

• It functions on continuously varying quantities.

• The output is usually represented in the form of graph.

• Its calculations are first converted in equation and later converted into electrical signals.

• The accuracy of the output is poor.

• It has limited memory space.

• It is not versatile, that is, it has limited application.

• The speed of analogue computer is low.

• Not suitable for business and industry.

Muhammad Aminu Ahmad Page 12


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

Digital Computers
A digital computer processes digital quantities that attain discrete values. They are machines made up
of combinations of chips, flip-flops, buttons and other electronic devices to make them function at a
very fast speed. A digital computer has its numbers, letters or other symbols represented in digital
format. A digital computer has the following characteristics:

• It operates by counting.

• It functions on discrete numbers.

• The calculations are converted into binary numbers, that is, 1s and 0s.

• The output is represented in the form of discrete values.

• Its accuracy is good.

• It has large memory space.

• It is versatile in nature and is suitable for a number of applications.

• It uses numbers, words and symbols.

• Its processing speed is high.

• It is highly suitable for business application.

Hybrid Computers
A hybrid computer possess the features of both analogue and digital computers. A hybrid computer
accepts either digital, analogue or both types of inputs and gives the results as per requirements
through special devices. Thus, with the hybrid computer, users can process both continuous and
discrete data. A converter is fixed in a hybrid computer to convert the analogue data into digital data
and vice versa. These are special purpose devices and are not widely used.
Super Computers
A super computer is the most powerful computer available at any given time. These machines are built
to process huge amounts of information and do so very quickly. Supercomputers are built specifically
for researchers or scientists working on projects that demand very huge amounts of data variables; an
example is in nuclear research, where scientists want to know exactly what will happen during every
millisecond of a nuclear chain reaction. To demonstrate the capability of super computers, for an air
pollution control project that involves more than 500,000 variables, it will take a mini computer about
45 hours to complete the simulation process, while a super computer completes the simulation in 30
minutes. Supercomputers are big in size, generate a lot of heat and are very expensive.

Muhammad Aminu Ahmad Page 13


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

Mainframe Computers
The largest types of computers that are common in use are the mainframe computers. They are
designed to handle tremendous amounts of input, output and storage. They are used mainly by large
organization. Other users access mainframe computers through terminals. Terminals consist of a
keyboard and a display. The mainframe is usually in a computer room.
Mini Computers
These are physically small compared to mainframes and are generally used for special purposes or
small-scale general purposes. The capabilities of mini computers is between mainframes and personal
computers. Like mainframes, they can handle a great deal more input and output than personal
computers. Although some minicomputers are designed for a single user, many can handle dozens or
even hundreds of terminals. Advances in circuitry enabled modern mini computers to out-perform
older mainframes.
Workstations
Workstations lie between mini computers and microcomputers in terms of processing power. A
workstation looks like a personal computer and is typically used by one person, although it is still
more powerful than the average personal computer. The differences in the capabilities of these types of
machines are growing smaller. They significantly differ from micro computers in two ways: the central
processing units of workstations are designed differently to enable faster processing of instructions.
Micro Computers/Personal Computers (PCs)
The term microcomputers and personal computers are used interchangeably to mean the small free-
standing computers that are commonly found in offices, homes and classrooms. Today, PCs are
seriously challenging older mainframes and mini computers in processing power and competition is
producing smaller and faster models of PCs every year. The following are different types of PCs:

• Desktop: This is the first type of PC and the most common. Most desktops are small enough to
fit on a desk, but are a little too big to carry around.

• Laptop: They weigh about 4.5kg, and are battery–operated computers with built–in screens.
They are designed to be carried and used in locations with no electricity. Laptops typically have
an almost full–sized keyboard.

• The Notebook: They are similar to laptops but smaller. They weigh about 2.7–3.2kg. As the
name implies, they are approximately the size of a notebook.

• The Palmtop: They are also known as personal digital assistance (PDAs) and are the smallest
of portable computers. Palmtops are less powerful than notebooks or desktops models and
have built-in applications such as word processing. They are mostly used to display important
informations such as telephone numbers and addresses.

Personal computers can do a lot of things. The most common tasks computers perform include writing
documents such as memos, letters, reports and briefs, budgeting and performing accounting tasks,

Muhammad Aminu Ahmad Page 14


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

analysing numeric information, searching through lists or reports for specific information, scheduling
and planning projects, creating illustrations, communication and many other activities.

1.5 Characteristics of Computers


The characteristics which make computer indispensable are speed, accuracy, reliability, storage capacity,
versatility and automation and diligence.

• Speed: A computer is able to process data and give the output in fractions of seconds, such
that the required information is given to the user on time, which enables the user to take right
decisions quickly. A powerful computer is capable of executing about 3 million calculations or
more per second.

• Accuracy: Apart from high processing speed, the accuracy of computers is consistently high
enough to avoid errors.

• Reliable: The output generated by the computer is very reliable. This is achieved when the data
passed as input to the computer and the instructions are correct and reliable.

• Storage: A computer has a provision to store large volumes of data in small storage devices,
which have capacity to store huge amounts of data and help the retrieval of data an easy task.

• Versatility: A computer performs three basic operations; it is capable of accessing and accepting
information from the user through various input-output devices. It performs basic arithmetic
and logic operations on the data as desired and it is capable of generating the desired output in
the desired form.

• Automation: The instructions fed into a computer works automatically without any human
intervention until the completion of execution of a program, or until the computer meets an
instructions to terminate execution.

• Diligence: The performance of a computer is consistent, that is, it does each and every calculation
with same speed and accuracy.

1.6 Components of a Computer


A computer has three main components; hardware, software and peripheral devices. Hardware refers to
the tangible and physical units of a computer system, which includes all electronic and electric circuitry
components and devices. Software is a set of instructions that makes the hardware work to get desired
results. Peripheral devices are machines and other electronic devices attached to the computer system
to perform a desired task. The components of a computer system are explained in Chapter 2.

Muhammad Aminu Ahmad Page 15


Chapter
2
Computer Hardware and Software

2.1 Introduction
The previous chapter presented an overview of computer systems, how they evolved, their categories
and characteristics. This chapter discusses the components of a computer, that is, hardware and
software.

2.2 Computer Hardware


The term hardware refers to all of the physical devices or components that a computer is made of. A
computer is not a single device, but a system of devices that work together. Each device in a computer
performs a particular function. Computer has hardware components such as central processing unit
(CPU), main memory, secondary storage devices, input and output devices. Computer hardware
performs some operations like addition, subtraction, data transfer and control transfers. Figure 2.1
presents the hardware component of a computer such as;

• The central processing unit (CPU)

• Main memory

• Secondary storage devices

• Input devices

• Output devices

2.2.1 Central Processing Unit (CPU)


When a computer is performing the tasks that a program commands, it is called running or executing
the program. The CPU is the component in the computer that runs programs. The term CPU is used
loosely to refer to the processor of a computer whether it is a set of chips or a single microprocessor.
The processor is the “brain” of the computer, that is, the part that interprets and executes instructions.

16
Kaduna State University CSC101 Lecture Note: 2017-2018 Session

Figure 2.1: Hardware Component of a Computer

In large computers, the processor often comprises a number of chips whereas in small computers called
microcomputers or PCs, the processor is a single silicon chip, called a microprocessor. Figure 2.2
presents an Intel microprocessor chip.

Figure 2.2: An Intel Microprocessor Chip

Every CPU has two basic parts, the control unit (CU) and the Arithmetic Logic Unit (ALU).
Control Unit (CU)
The control unit manages all the computer resources and coordinates all the activities of a computer.
The control unit contains the basic instructions (called firmware) for executing programs. The
instruction set, built into the circuitry of the control unit, is a list of all the operations that the CPU
can perform. In fact, the control unit directs the flow of data around the CPU and the computer.
Based on the instructions given, the CPU ensures that the operation specified in the program are
performed in the sequence. This operation may be receipt of data and storing them at specified
locations, transfer of data from one address of memory to another, transfer of data from memory to
the ALU and controlling the ALU.

Muhammad Aminu Ahmad Page 17


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

Arithmetic and Logical Unit (ALU)


All calculations and comparisons (decisions) are made in the Arithmetic and Logic Unit (ALU) of the
CPU. Processing does not occurs in the primary storage. Intermediate results generated are temporarily
placed in a designated working storage area until needed at a later time. Data may thus move from
primary storage to the ALU and back again many times before processing is finished. Once completed,
the final results are released to an output storage section and from there to an output device. The type
and number of ALU operations a computer can perform are determined by the design of the CPU.
2.2.2 Primary Storage Devices
The data passed to the computer is stored in the memory. When the data are required to be processed
or operated upon, it is then transferred to the ALU, which does all the computation work such as
addition, subtraction and shifting. After processing, the data are again brought back and stored in the
memory. There are two main types of memories; main memory and read only memory (ROM).
Main Memory (RAM)
The main memory, commonly known as random-access memory (RAM), can be seen as the work area
of a computer. This is where the computer stores a program while the program is running, as well as
the data that the program is working with. Main memory is called RAM because the CPU is able to
quickly access data stored at any random location. Main memory is usually a volatile type of memory
that is used only for temporary storage while a program is running. When the computer is turned off,
the contents of RAM are erased. Figure 2.3 shows a main memory or RAM chip.

Figure 2.3: A main memory Chip

Read Only Memory (ROM)


Instructions to perform operations that are critical to a computer are stored permanently on a read-only
memory (ROM) chip, which is installed by the manufacturer inside the computer. When the power
in the computer is turned off, the instructions stored in ROM are not lost and the data cannot be
changed, thus they are non-volatile. Figure 2.4 shows a ROM chip.

Muhammad Aminu Ahmad Page 18


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

Figure 2.4: A ROM Chip

ROMs are categorised as follows:

• Programmable Read Only Memory (PROM): These are non-volatile memories and may
be written into only once. The writing process is performed using special equipment for writing.
However, PROMs provide flexibility and convenience.

• Erasable Programmable Read Only Memory (EPROM): These are another variation of
read only memories called read-mostly memories. EPROMs can be read and written into as
with the PROMs. Before write operations, the content must be erased by exposing the memory
to ultraviolet radiation. EPROMs have multiple update capacity, that is, they can be erased
repeatedly.

• Electrically Erasable Programmable Read Only Memory (EEPROM): These are read-
mostly memories that can be written into at any time without erasing prior content; only the
byte address are updated. The write operation takes considerably longer time than the read
operation. EEPROM is non-volatile, flexible and more expensive than the EPROM.

Table 2.1 presents differences between RAMs and ROMs

Muhammad Aminu Ahmad Page 19


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

Table 2.1: Differences between RAM and ROM

Random-Access Memory (RAM) Read-Only Memory (ROM)


The data and program in RAM can be read The data or program in ROM can only be
and written. read but cannot be changed.
RAM stores data during and after processing. ROM is another type of memory that is
RAM is also known as a working memory. permanently stored inside the computer.
RAM is volatile which means the programs ROM is non-volatile. It holds the programs
and data in RAM are lost when the computer and data when the computer is powered off.
is powered off.
A computer uses RAM to hold temporary Programs in ROM are prerecorded. It can
instructions and data needed to complete only be stored by the manufacturer.
tasks. This enables the CPU (Central
Processing Unit) to access instructions and
data stored in the memory very quickly

2.2.3 Secondary Storage Devices


Secondary storage is a type of memory that can hold data for long period of time, even when there is
no power to the computer. Programs are normally stored in secondary memory and loaded into main
memory as needed. Important data, such as word processing documents, payroll data and inventory
records are stored in secondary storage as well. The most common type of secondary storage device is
the disk drive. Figure 2.5 shows some storage devices.

Figure 2.5: Storage devices

Disk Drive
A disk drive stores data by magnetically encoding it onto a circular disk. Most computers have a
disk drive mounted inside their cases. External disk drives, which connect to one of the computer’s
communication ports, are also available. External disk drives can be used to create backup copies of

Muhammad Aminu Ahmad Page 20


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

important data or to move data to another computer. In addition to external disk drives, many types
of devices have been created for copying data, and for moving data to other computers.
Floppy Disk Drive
A floppy disk drive records data onto a small floppy disk, which can be removed from the drive. Floppy
disks hold a small amount of data, are slow to access data and can be unreliable. Floppy disk drives
are no longer in use in the recent years.
Universal Serial Bus (USB) Drives
USB drives are small devices that plug into the computer’s USB port, and appear to the system as a
disk drive. These drives do not actually contain a disk. They store data in a special type of memory
known as flash memory. USB drives, which are also known as memory sticks and flash drives, are
inexpensive, reliable and small enough to be carried in pocket.
Optical Devices
Optical devices such as the compact disc (CD) and the digital versatile disc (DVD) are also popular
for data storage. Data are not recorded magnetically on an optical disc, but is encoded as a series of
pits on the disc surface. CD and DVD drives use a laser to detect the pits and thus read the encoded
data. Optical discs hold large amounts of data, and because recordable CD and DVD drives are now
common, they are good mediums for creating backup copies of data.
Flash Cards
Flash cards can be used to store gigabytes of data depending on how much memory they have. There
are three different types of flash cards: compact flash cards, smart media cards and memory sticks.
2.2.4 Input and Output Devices
Input is any data the computer collects from a user and other devices. The component that collects
data and sends it to the computer is called an input device. After the computer has received and
processed the data, the final result has to be brought out from the machine in some intelligent and
readable form. The result that comes out of the machine is called output and the equipment which
enables the results to be brought out are termed output devices. Output is any data the computer
produces for people or for other devices. It might be a sales report, a list of names or a graphic image.
The data are sent to an output device, which formats and presents it.
Common input devices are the keyboard, mouse, scanner, microphone, joy stick, light pens, digital
camera, visual displays, printers, projector, speaker disk drives and optical drives as shown in Figure
2.6

Muhammad Aminu Ahmad Page 21


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

Figure 2.6: Input Devices

Keyboard
A keyboard is the most common input device and is used for all kinds of computers. Several kinds of
keyboards are available but they resemble each other with minor variations. The keyboard in most
common use is the QWERTY board. IBM and IBM compatible PCs use 101 keyboard, which has 101
keys.
Mouse
A mouse is an electro-mechanical hand-held device. It is used as a pointer to select menu commands,
move icons, size windows, start programs and choose options. Thus, the mouse is best used as a
pointing and selecting device, as it allows moving the cursor across the screen of a computer in a rapid
and intuitive way. Buttons are mounted on the chassis of the mouse to trigger some events, like the
selection of an icon or menu item the cursor is positioned over. Mice are of two types:

• Mechanical mice: These contain a small ball inside the chassis, which is spun as the mouse is
moved over the surface. The ball in turn rotates some small wheels whose motion is encoded by
potentiometers or optical encoders. These mice can work on every surface, but dirt is collected
by the ball and often soils the encoders.

• Optical mice: These do not need a rotating ball, they contain optical sensors that emit signals
as the mouse is moved over a special grid containing reflecting lines in the X and Y direction; on
every line that is crossed, a pulse is emitted. These mice have the advantage that there are no
moving parts and no dirt is collected from the surface, but they work only in combination with a
special mouse pad containing the grid.

Muhammad Aminu Ahmad Page 22


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

Track Balls
The trackball is somehow the inverse of the mouse. It consists of a fixed chassis and a freely rotating ball
that can be moved in any direction with the fingers or the palm of the hand; small wheels, positioned
90 degrees from each other, are connected to the ball and rotate as it is spun. In mechanical trackballs,
the spinning ball is connected to potentiometers whose output corresponds to changes in the X and Y
direction. In optical trackballs, optical encoders are used to generate pulses according to the increments
in rotation around the X and Y axis. Trackballs have the same purpose as the mouse, to move a cursor
across the screen, but are preferable when there is no enough space for a mouse or when the cursor has
to be moved rapidly over a large area, because the ball can be spun very fast and the cursor can be
moved continuously without stopping.
Joy Stick
Joysticks consist of a stick that is mounted vertically on a fixed base, which can be rotated around two
orthogonal axes. There exist three basic types of joysticks employing different technologies; digital,
displacement and force joysticks.

• The digital joystick does not have resistors, but switches mounted around the base of the lever
(usually four), so that movement in any of the eight directions can be sensed. The output is "on"
or "off" in any of the eight directions, and not proportional to the stick’s displacement. Digital
joystick cannot be used in absolute positioning mode, but only to send directional information.
This kind of joystick is extremely successful in arcade games because of its robustness, simplicity
and low cost.

• In displacement joysticks, the stick is connected to resistors, typically potentiometers, whose


resistance is proportional to the stick’s position along the two axes. Increasing the force applied
to the stick increases its displacement; there is a direct relation between force and displacement.
The joystick can be used as an absolute positioning device where the vertical stick corresponds
to a central position and the full deflection corresponds to corner positions (absolute mode), or
the deflection may be used as a velocity parameter indicating the direction and the speed of
movement of a cursor (relative parametric mode).

• Force joysticks has a lever that is rigid and cannot be moved noticeably, because the forces
applied to the stick are measured not the motion. The output of force joysticks is proportional to
the direction and amount of force applied. Force joysticks always return to their central position
when released. Because of their extremely limited movement, they are not suited for absolute
positioning.

Touch Pen and Screens


Touch Pens are devices used to directly point on the screen to select menu items or icons, or directly
draw graphics on the screen. It can also be used for writing on a special pad as direct written
information to a system. Pressure on tip of a button is used to cause same action as right-button-click
of a mouse.

Muhammad Aminu Ahmad Page 23


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

Touch screens are simple intuitive and easiest to learn of all input devices. Touch screen enables
users to choose the desired icon or menu items displayed on the screen by simply touching with their
fingers.
Scanner
A scanner is a device that captures images from photographic prints, posters, magazine pages and
similar sources for computer editing and display.
Visual Display
Visual display is an output device that enables a user to see the results produced by the computer. It
is available in different sizes. Colour monitors and liquid crystal displays (LCD) are very popular these
days. The quality of the display depends on the screen resolution.
Printer
A printer is a device that prints text or illustrations on paper. There are many different types of
printers

• Dot-Matrix Printers: These are character printers that form characters and all kind of images
as a pattern of dots. Dot-matrix prints many special characters, different sizes of print and
graphics such as charts and graphs. They are slow, with speed usually ranging between 30 to 600
characters per second.

• Ink-Jet printers: These are character printers that form characters and all kind of images by
spraying small drops of ink on to the paper. The print head contains up to 64 tiny nozzles that
can be selectively heated up in a few micro seconds by an integrated circuit register. They are
slower than dot-matrix printers with speed usually ranging from 40 to 300 characters per second.

• Laser Printers: These are line printers that print one line at a time. They have a solid cylinder
drum with characters embossed on its surface in form of circular bands. Laser printers can only
print a pre-defined set of characters in a pre-defined style that is embossed on the drum. They
speed in the range of 300 to 2000 lines per minutes.

• Multifunction Device: As its name implies, a multifunction printer can perform more than
one task. This device can usually operate as a fax machine, copier, and scanner in addition to its
traditional printing duties.

Plotter
A plotter is a special printer that is used to create posters and blueprints.
Projector
A Liquid Crystal Display (LCD) projector is a device that uses its own light source to project what is
to be displayed on a wall or projection screen. A digital light processing (DLP) projector uses tiny
mirrors to reflect light which can be seen clearly in a well-lit room.

Muhammad Aminu Ahmad Page 24


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

Speakers
A speaker is a device that produces out music, speech or other sounds. A pair of speakers is an audio
output device that generates sound. The headphone is a pair of small speakers placed over the ears
and plugged into a port on the sound card. A woofer or sub-woofer is used to boost the low bass sound
and is connected to the port on the sound card.
Modem
A modem (MOdulator-DEModulator) converts signal from digital to analogue (modulation) and
analogue to digital (demodulation). The modem enables digital microcomputers to send output
through analogue telephone lines; voice and data can be carried over through the modem. The
modem is not only an output device but also an input device that receives data and voice through a
communication channel.

2.3 Computer Software


Computer software is the set of instructions that makes the computer work as desired. Essentially,
computer software can be divided into three main groups depending on their use and application.
These are system software, middleware and application software. Usually most of us interact with a
computer using computer software developed as application software.
2.3.1 System Software
The programs that control and manage the basic operations of a computer are generally referred to as
system software. System software typically includes the following types of programs:
Operating Systems (OS)
An operating system is the most fundamental set of programs on a computer. The operating system
controls the internal operations of the computer’s hardware, manages the devices connected to the
computer, allows data to be saved to and retrieved from storage devices, and allows other programs
to run on the computer. Operating system is the software used by the computer to translate inputs
from various sources into a language which a machine can understand. Basically, the operating system
coordinates the different hardware components of a computer. The most popular operating systems
are Linux (e.g Redhat, Ubuntu, Fedora), Microsoft Windows (e.g Windows 7, 8 and 10), Mac OS X
and UNIX (e.g Solaris).
Functions of Operating Systems
The operating system has the following primary functions:
• Booting of the Computer: This is the first process that takes place the moment the computer’s
electrical switch is put on. During this process all the peripherals connected to the computer are
checked and validated. At the end of the validation process, the operating system signals the
user to begin working on the computer.

• Providing User Interface: Operating system provides an interface for the user, either as a
command line interface or as a graphical user interface. This enables the user to communicate

Muhammad Aminu Ahmad Page 25


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

with the computer. In other words, operating system communicates with the computer user or
operator by means of terminals and through the use of monitor command responses. The user
may also be able to communicate with the operating system by means of command language.
There are two broad categories of interfaces: command line and graphical user interfaces. To use
an operating system with a command line interface, a user can type words and symbols using
the keyboard. With a graphical user interface (GUI), a user selects actions by using a mouse or
similar pointing device to click on pictures called icons or to pick options from menus. Every
operating system provides a user interface, whether it is made up of text or is graphical in nature.

• Managing the Hardware: Operating system controls and manages hardware resources. For
example, operating system manages the selection and operation of devices used for input, output
and storage. In other words the operating system serves as the intermediary between programs
and hardware. Regardless of the type of user interface, the operating system intercepts commands
to use memory and other devices, keeping track of what programs have access to what devices
and so on. For example when instructing the operating system to list the files in a directory or
folder, the software interpreting the command sends a request to the CPU in form of interrupting
the CPU and instructing the CPU to go to the disk drive and retrieve the names of the files it
finds in the directory or folder.

• Managing the File System: Operating system groups data together into logical compartments
for storage on disk. These groups of data are called files. The computer stores information in files.
Files may contain program instructions or data created or used by a program. The operating
system maintains the list of files on a disk.

• Supporting Programs: Another major function of an operating system is to provide services


to other programs. Often these services are similar to those that the operating system provides
directly to users. For example when a user wants word processing program to retrieve a document,
the word processor will list the files in the directory that the user specifies. To do this, the
program (word processing) calls on the operating system to list the files. The operating system
goes through the same process to build a list of files whether it receives instruction directly from
a user or from an application program. But when the request comes from an application the
operating system sends the result of its work to the application program instead of directly to the
computer screen. Some of the other services that an operating system provides to programs are:

– Saving files to disk and reading them from disk into memory .
– Checking available disk or memory space,
– Allocating memory to hold data for a program.
– Reading keystrokes from the keyboard.
– Displaying characters or graphics on the screen.
– Loading the user program into memory.
– Giving instruction to display the result on the monitor

Muhammad Aminu Ahmad Page 26


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

Categories of Operating Systems


Operating systems are designed with many objectives in mind. Among the most basic questions in
operating system design are the following:

Should the operating system be able to do more than one thing at a time?
Should the operating system support only one user or should it support multiple users
simultaneously?
Should the operating system be able to use more than one CPU?

The categories of operating systems are;

• Multitasking Operating System/Multi Programming: This is an operating system that


is capable of running more than one program task per operation time. There are two types of
multitasking operating systems; cooperative and pre-emptive.

– Cooperative Multitasking: This requires cooperation between the operating system and
application programs. In this case, the programs are written in such a way that they
periodically check with the operating system to determine whether any other program needs
the CPU. If a program needs the CPU, they relinquish control of the CPU to the next
program. Cooperative multitasking is common with Macintosh OS and computers running
Microsoft Windows.
– Pre-emptive Multitasking: Under this scheme, the operating system maintains a list of
processes (programs) that are running. Each process on the list is assigned a priority by the
operating system when it is started. At any time, the operating system can intervene and
modify the priority list. The operating system also retains control of the amount of time
that it spends with any process before going to the next process. Unix, OS/2 and Windows
NT employ pre-emptive multitasking.

• Multi-user Operating Systems: A multi-user operating system allows more than a single
user access to a computer at the same time. To accomplish this, a multi-user operating system
must also be capable of multitasking. Multi-user operating system provides two ways to enable
people use the same PC at the same time.

– The first way to connect to a PC running multi-user operating system is from another
computer with a connection. The remote user can log in and run programs, list files, send
e-mails read the news and otherwise do everything they could do as if they are physically in
front of the computer.
– The second way to connect to a computer, with multi-user operating system, is by attaching
terminals to the PC. Terminals are inexpensive devices that consist of a keyboard and a
monitor.

• Multiprocessing Operating Systems: A special type of operating system is required to


use a computer equipped with more than one CPU. In other words, multiprocessing requires

Muhammad Aminu Ahmad Page 27


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

an operating system that is capable of using and managing a series of CPUs. There are two
types of multiprocessing operating systems; asymmetric and symmetric. With asymmetrical
multiprocessing, one main CPU retains the overall control of the computer as well as that of the
other microprocessors. In symmetrical multiprocessing, there is no single controlling CPU. This
arrangement provides a linear increase in system capacity for each processor added to the system.

2.3.2 Middleware
Middleware is a set of services that allows multiple processes running on one or more machines to
interact. Middleware is often used to support and simplify complex distributed applications. It can
also allow data contained in one database to be accessed through another. Middleware is sometimes
called plumbing because it connects two applications and passes data between them. (e.g Java RMI,
CORBA, DCOM, web servers, application servers, etc.).
2.3.3 Application Software
These are programs that make a computer useful for everyday tasks. These are the programs that
people normally spend most of their time running on their computers. Popular examples of application
software are word processing programs, image editing programs, spreadsheet programs, database
programs, email programs, web browsers and games.
Word processing
This is one of the most common application software. The great advantage of word processing over
using a typewriter is that you can make changes without retyping the entire document. Word processors
make it easy to manipulate and format documents. Example of word processing software is Microsoft
Office Word and Open Office Word.
Spreadsheets
These are computer programs that allow users to electronically create and manipulate spreadsheets
(tables of values arranged in rows and columns with predefined relationships to each other). Spreadsheets
are used for mathematical calculations such as accounting, budgeting, statistics and so on. Examples
of spreadsheet applications are Microsoft Excel, Open Office Spreadsheet, Lotus and SPSS.
Database Management Systems
These applications are computer programs that let people create and manipulate data in a database.
A database is a collection of related information that can be manipulated and used to sort information,
conduct statistical analyses or generate reports. Examples of database management systems are
Microsoft Access, Microsoft SQL, MySQL and Oracle database.
Presentation Packages
A presentation is a means of assessment, which requires presentation providers to present their work
orally in the presence of an audience. It combines both visual and verbal elements. A presentation
software allows users to create presentations by producing slides or handouts for presentation. Essentially,
such computer programs allow users to create a variety of visually appealing electronic slides for

Muhammad Aminu Ahmad Page 28


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

presentation. They enable users to create highly stylized images for slide presentations and reports.
They can also be used to produce various types of charts and graphs. Microsoft PowerPoint and Prezi
are examples of presentation application.
Image Editors
Image editor programs are designed specifically for capturing, creating, editing, and manipulating
images. These graphics programs provide a variety of special features for creating and altering images.
In addition to offering a host of filters and image transformation algorithms, some image editors also
enable users to create and superimpose layers. Most graphic programs have the ability to import
and export one or more graphic file formats. With image editing software, one a user can adjust an
image to improve its appearance, darken or lighten an image, rotate it, adjust it contrast, crop out
extraneous detail and much more. Examples of image editors are Adobe Photoshop, Adobe Illustrator
and CorelDraw.
Communication Packages
These are applications that enable people to send faxes and emails and dial into other computers for
voice and video communication. Examples are Microsoft Outlook and Skype.

Muhammad Aminu Ahmad Page 29


Chapter
3
Data Representation and Processing

3.1 Introduction
The word "data" is the plural of datum, which means fact, observation, assumption or occurrence. More
precisely, data are representations of facts pertaining to people, things, ideas and events. Data are
represented by symbols such as letters of the alphabets; student names and product names, numerals;
employee number or other special symbols. Data processing refers to generating and organising data in
a useful way. People and organisation generate data to keep record of activities, events and transactions.
Data collection, processing, storage and retrieval can be facilitated using a computer system. This
chapter discusses how data are represented and processed in computers.

3.2 Data Representation


All information in the computer is handled using electrical components like the integrated circuits and
semiconductors, all of which can recognize only two states; presence or absence of an electrical signal.
Two symbols used to represent these two states are 0 and 1, and are known as BITS (an abbreviation
for BInary digiTS). A zero (0) represents the absence of a signal and one (1) represents the presence of
a signal. Therefore, a BIT is the smallest unit of data in a computer and can either store a 0 or 1. Since
a single bit can store only one of the two values, there can possibly be only four unique combinations:

00 01 10 11

Therefore, bits are combined together into larger units in order to hold greater range of values.
NIBBLES are four sequence of bits. BYTES are typically a sequence of eight bits put together to
create a single computer alphabetical or numerical character.
Bytes are used to quantify the amount of data digitally stored (on disks, tapes) or transmitted
(over a network), and are also used to measure the memory and document size. A CHARACTER is
represented by one byte. It can be a letter, digit, punctuation mark or special characters. A WORD
is a combination of 2 bytes or more. Bytes may appear as Kilobytes (210 = 1024 bytes), Megabytes

30
Kaduna State University CSC101 Lecture Note: 2017-2018 Session

(220 = 1, 048, 576 bytes), Gigabytes (230 = 1, 073, 741, 824 bytes), Terabytes (240 = 1, 099, 511, 627, 776
bytes), or Petabytes (250 = 1, 125, 899, 906, 842, 624 bytes).
3.2.1 Representing Text
Text is represented in a computer using an agreed unique code for every letter, number and symbol
that needs to be presented. Each code consists of a fixed-length and unique sequence of bits. A word
can then be ‘written’ by determining the code for each letter and putting them together. The common
agreed code for text representation in computer is the ASCII (American Standard Code for Information
Interchange). ASCII uses 8-bit strings or one byte to represent an alphabet. Appendix A presents an
overview of the ASCII code. Therefore, the text “A Computer” can be encoded as follows:

A C o m p u t e r
01000001 100000 01000011 01101111 01101101 01110000 01110101 01110100 01100101 01110010

Therefore, text files generally contain long sequences of code (mostly ASCII) as described above. A
text editor translates the sequence of code into a human readable format and the other way round.
3.2.2 Representing Numbers
The ASCII (or Unicode) table in Appendix A includes codes for the representation of numbers. However,
this is not an ideal way of representing numbers if they are used within a calculation. The ASCII
code uses 8 bits or one byte to represent a single-digit number, therefore the largest number that
can be stored is 9. However, if numbers are represented in binary (rather than decimal), 8 bits can
represent numbers from 0 to 127. There is also an advantage of having a number translated into
a different numeric system (i.e. the binary system) where it remains a number and where hence
mathematical calculations can still be conducted. Binary numbers are represented using bit sequences.
The representation follows the same simple principle as the decimal system.
The binary system uses 2 as its base with the digits 0 and 1. Therefore the binary number 10110102
eqauls 9010 and vice versa:

1011010 = 0×20 + 1×21 + 0×22 + 1×23 + 1×24 + 0×25 + 1×26 = 0 + 2 + 0 + 8 + 16 + 0 + 64 = 9010

90
2 = 45 remainder 0

45
2 = 22 remainder 1

22
2 = 11 remainder 0

11
2 = 5 remainder 1

5
2 = 2 remainder 1

2
2 = 1 remainder 0

1
2 = 0 remainder 1

Muhammad Aminu Ahmad Page 31


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

3.2.3 Representing Images


Computers represent an image by dividing the image into many small picture elements known as pixels.
The appearance of each pixel is then encoded in binary coded form. The collection of these encoded
pixels is known as the bitmap of the image. The method that is used to encode the individual pixels
of a bitmap varies. For example, a black and white image can be represented using a single bit for
each pixel. More sophisticated black-and-white pictures with varying shades of grey may use 8-bit
sequences (a byte) for each pixel to represent the different shades. A colour image usually uses three
bytes to represent a single pixel. For example, computers frequently use a combination of red, green
and blue to represent a wide spectrum of colour (the RGB colour model). Accordingly, the colour of a
pixel can be represented using three bytes, each representing the intensity of the colours red, green and
blue. Files that store a bitmap image can be rather large, and various compression methods have been
developed to reduce their size. Graphic Interchange Format (GIF), for example, is one such method
that reduces the size of a bitmap file by reducing the number of colours that can be assigned to a pixel
to 256, and the Joint Photographic Experts Group (JPEG) developed a compression method which is
commonly used to compress photographs.
3.2.4 Representing Sounds
Sounds are represented in a computer by converting the analogue sound signal into a digital format.
This is achieved by checking and recording the amplitude of the sound wave at regular time intervals.
The recorded values can then be stored in binary form and used to re-construct the initial wave at a
later stage. The sampling frequency used when recording a CD is 44,100 samples per second (44.1 kHz
sample rate), and the sample data are recorded as a 16-bit sequence (32 bits for stereo recordings). For
example, the MIDI (Musical Instrument Digital Interface) files is an approach to recording music that
is frequently used in the music synthesisers used for video games or annotation on websites. MIDI files
generally require less memory space, because they store music in the form of parameters that describe
the music, such as, for example, the note to be played, the volume, the tempo, and so on. This usually
requires less storage space than sampling at a rate of 44.1 kHz. The Motion Picture Expert Group
(MPEG) also developed various standards to compress both audio and video files. For example, the
MP3 (which is short for MPEG layer 3) is a system that compress audio. Compression methods are
used to reduce storage space and ensure that sound files can be easily transmitted across network
transmission media.

3.3 Data Processing


Data in raw form cannot solve any problem. The data need some processing to make it useful. Data
processing is the conversion of data into a more useful form; handling or manipulating data in some
fashion. Regardless of the activities involved in it, processing tries to assign meaning to data. Thus,
the ultimate goal of processing is to transform data into information. Data processing is the process
through which facts and figures are collected, assigned meaning, communicated to others and retained
for future use. Thus,

Data processing is a series of actions or operations that converts data into useful information.

Muhammad Aminu Ahmad Page 32


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

Data processing system is the resources used to accomplish the processing of data.

3.3.1 Information
Information refers to data that has been transformed into a meaningful and useful form for specific
purposes. The result obtained by data processing is called information. However, information produced
in one data processing step may be used as data in another data processing step. Although data are
generally not useful unless it is manipulated and organised into meaningful form, in some cases, data
may not require any processing before constituting information. Information is identified and defined
by its users, that is, determining when data become information depends on user requirements. For
example, purchase data, such as your name, address, the number of items purchased, the price, the tax
and the amount you paid, are data items when considered separately. However, putting these items
together, they represent information about a business transaction. Similarly putting together student
name, number, department, course, etc., represent information about student registration.
3.3.2 Data Processing Activities
Data processing comprises activities that are necessary to transform data into information. This can
be achieved through the following:

• Manual Data Processing: Data are processed manually without the help of mechanical devices.
The data processing is performed using tools such as abacus, slide rule, Napier bones etc.

• Mechanical Data Processing: Mechanical devices such as calculators, tabulators, etc., are
used for data processing.

• Electronic Data Processing: The data are processed using a computer.

As the complexity of data processing increased, the need for high performance data processing systems
increased. Therefore, the use of electronic data processing outperformed the use of manual and
mechanical methods. Data processing requires various functions and activities that can be grouped
under five basic categories; collection, conversion, manipulation, storage and communication.
Collection
Data originate in the form of events or some observations. The data are then recorded in some usable
form. Data may be initially recorded on paper source documents and then converted into a machine
usable form for processing. Alternatively, the data may be recorded by a direct input device in a
paperless, machine-readable form. Data collection is also termed as data capture. Data collection
implies that the raw data are collected and set out in the form of original document called a source
document.
Conversion
Once the data are collected, they are converted to a form that is more suitable for processing. The
data are first codified by assigning identification codes. A code comprises of numbers, letters, special
characters or a combination of these. For example, an employee may be allotted a code as 5253162,

Muhammad Aminu Ahmad Page 33


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

his category as S or J class. It is useful to codify data, when data require classification. To classify
means to categorize, that is, data with similar characteristics are placed in similar categories or groups.
After classification of data, it is verified or checked to ensure the accuracy before processing starts.
After verification, the data are transcribed from one data medium to another. For example, in data
processing using a computer, the data may be transformed from source documents to machine sensible
form using magnetic tape or a disk.
Manipulation
Once data are collected and converted, they are ready for the manipulation function, which converts
data into information. Manipulation consists of following activities:

• Sorting: It involves the arrangement of data items in a desired sequence. Usually, it is easier
to work with data if it is arranged in a logical sequence. Most often, the data are arranged
in alphabetical sequence. Sometimes sorting itself will transform data into information. For
example, a simple act of sorting the names in alphabetical order gives meaning to a telephone
directory. The directory will be practically worthless without sorting. Business data processing
extensively utilises sorting technique. Virtually all the records in business files are maintained in
some logical sequence. Numeric sorting is common in computer-based processing systems because
it is usually faster than alphabetical sorting.

• Calculating: This is the arithmetic manipulation of data. Items of recorded data can be
added to one another, subtracted, divided or multiplied to create new data. Calculation is an
integral part of data processing. For example, in calculating an employee’s pay, the hours worked
multiplied by the hourly wage rate gives the gross pay. Based on total earning, income-tax
deductions are computed and subtracted from gross-pay to arrive at net pay.

• Summarizing: To summarize is to condense or reduce masses of data to a more usable and


concise form. When the data involved is numbers, you summarize by counting or accumulating
the totals of the data in a classification or by selecting strategic data from the mass of data being
processed. For example, in summarizing a business activity, a general manager may be provided
with sales-totals by major product line or sales totals by individual salesman.

• Comparing: This is to perform an evaluation in relation to some known measure. For example,
business managers compare data to discover how well their companies are doing. They many
compare current sales figures with those for last year to analyse the performance of the company
in the current month.

Managing the Output Results


Once data are captured and manipulated, the following activities may be performed:

• Storing: This is to hold data for continued or later use. Storage is essential for any organised
method of processing and re-using data. The basic requirement for utilizing the computer is
the ability to store and access data. The storage mechanisms for a computer are magnetic

Muhammad Aminu Ahmad Page 34


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

disks/magnetic tapes. The storing activity involves storing data and information in organised
manner in order to facilitate the retrieval activity. The data should be stored only if the value of
having them in future exceeds the storage cost.

• Retrieving: This is the process of searching or locating a data item from the storage. using
a computer, the data is retrieved from the storage device in sequential, indexed sequential or
random access mode.

Communication
Communication is the process of sharing information. Unless the information is made available to the
users who need it, it is worthless. Thus, communication involves the transfer of data and information
produced by the data processing system to the prospective users of such information or to another
data processing system. As a result, reports and documents are prepared and delivered to the users.
Using a computer, results are communicated through display units or terminals or printed out.
Reproduction
To reproduce is to copy or duplicate data or information. This reproduction activity can be done using
a computer.
3.3.3 The Data Processing Cycle
The data processing activities described above can be grouped in four functional categories constituting
what is known as a data processing cycle (also called Information Processing Cycle); data input, data
processing, data output and data storage.

• Input: The term input refers to the activities required to record data and to make it available
for processing. The input can also include the steps necessary to check, verify and validate
data contents. A computer can accept data (input) from a wide range of input devices such as
keyboards, mouse, microphones scanners etc.

• Processing: The term processing denotes the actual data manipulation techniques such as
classifying, sorting, calculating, summarizing, comparing, etc., that convert data into information.
Computer circuits perform calculations on numbers. They are also capable of manipulating
numerics and other symbols used in text with equal efficiency. A computer also possesses the
ability to perform logic operations. For example, if we compare two items represented by the
symbols A and B, there are only three possible outcomes. A is less than B (A<B); A is equal to B
(A=B): or A is greater than B (A>B). A computer can perform such comparisons and, depending
on the result, follow a predetermined path to complete its work. This ability to compare is an
important property of computers.

• Output: This is a communication function which transmits the information generated to the
needed person. Sometimes output also includes decoding activity which converts the electronically
generated information into human-readable form. A computer can supply processed data
(information) to a wide range of output devices such as display screens and printers.

Muhammad Aminu Ahmad Page 35


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

• Storage: This involves the filing of data and information for future use. Both data and program
instructions are stored internally in a computer. Once they are stored in the internal memory,
they can be called up quickly or retrieved for further use.

Thus, a computer is a data processing system that uses data as input and processes the data to produce
information as output. These achieve the function of data processing cycle. The four basic function
are performed in a logical sequence as presented in Figure 3.1.

Storage Processing output


Data and Sorting Data and
Storing Information Calculating Information Communicate
and Retrieving Summarizing Reproduce
Comparing

Data

Collecting
Converting

Input

Figure 3.1: Data processing life cycle

3.3.4 Data Organisation


Data can be arranged or organised in a variety of ways, before using a computer for processing. The
hierarchical approach to organisation of data is generally recommended.

• Data Item: A data item is the smallest unit of information stored in a computer file. It is a
single element used to represent a fact such as an employee’s name, student number, item price,
etc.

• Field: Data items are physically arranged as fields in a computer file. Their length may be fixed
or variable. For example a student identification number that uses eight digit has a fixed field
length. In contrast, name varies considerably from one student to another, therefore student
names has variable field length.

• Record: A record is a collection of related data fields. Each record normally corresponds to a
specific unit of information.

• Database: The collection of related files is called a database. A database contains all the related
files for a particular application.

Muhammad Aminu Ahmad Page 36


Chapter
4
Networks

4.1 Introduction
The previous chapters presented an overview of computer systems and their components and the use
of computer in data processing. This chapter discusses the use of computers in creating a network for
communication and sharing information and other resources.

4.2 Computer Networks


A computer network is a collection of computers and other hardware components interconnected by
communication channels that allow sharing of resources and information. Two devices are said to be in
a network if at least one process in one device is able to send/receive data to/from at least one process
residing in a remote device. Simply, two or more computers interconnected through a communication
medium for information interchange is called a computer network.
4.2.1 Network Types
Networks come in a wide variety of types. The most common are local area networks (LANs) and
wide area networks (WANs), but there are many other types of networks, including metropolitan area
networks (MANs), storage area networks (SANs), intranets and extranets. The following sections
provide a brief overview of each of these network types.
Local Area Network (LAN)
A local area network (LAN) is a network that connects computers and devices in a limited geographical
area such as home, school, computer laboratory, office building, or closely positioned group of buildings.
Each computer or device on the network is a node. Current wired LANs are most likely to be based on
Ethernet technology, although new standards like ITU-T also provide a way to create a wired LAN
using existing home wires (coaxial cables, phone lines and power lines).

37
Kaduna State University CSC101 Lecture Note: 2017-2018 Session

Wide Area Network (WAN)


Wide area networks are used to connect LANs together. Typically, WANs are used when the LANs
that must be connected are separated by a long distance. WANs are leased from carrier networks,
such as telephone companies. Four basic types of connections, or circuits, are used in WAN services:
circuit-switched, cell-switched, packet-switched, and dedicated connections. A wide array of WAN
services are available, including analogue dialup, ATM, dedicated circuits, cable, DSL (digital subscriber
line) Frame Relay, ISDN, Switched Multi-megabit Data Services (SMDS), and X.25. Analog dialup
and ISDN are examples of circuit switched services, ATM and SMDS are examples of cell-switched
services, and Frame Relay and X.25 are examples of packet-switched services.
Metropolitan Area Network (MAN)
A metropolitan area network (MAN) is a hybrid between a LAN and a WAN. Like a WAN, it connects
two or more LANs in the same geographic area. A MAN, for example, might connect two different
buildings or offices in the same city. A MAN provides high-speed connections, such as T1 (1.544 Mbps)
and optical services. The optical services provided include SONET (the Synchronous Optical Network
standard) and SDH (the Synchronous Digital Hierarchy standard). With these optical services, carriers
can provide high-speed services, including ATM and Gigabit Ethernet. These two optical services
provide speeds ranging into the hundreds or thousands of megabits per second (Mbps). Devices used
to provide connections for MANs include high-end routers, ATM switches and optical switches.
Storage Area Network
A storage area network (SAN) is a dedicated network that provides access to consolidated, block
level data storage. Storage area networks are primarily used to make storage devices, such as disk
arrays, tape libraries and optical jukeboxes, accessible to servers so that the devices appear like locally
attached devices to the operating system. A SAN typically has its own network of storage devices that
are generally not accessible through the local area network by other devices.
Intranet
An Intranet is basically a network that is local to a company, that is, users from within the company
can find their resources without having to go outside of the company. An Intranet can include LANs,
private WANs, MANs and SANs.
Extranet
An extranet is an extended intranet, where certain internal services are made available to known
external users or external business partners at remote locations. The connections between these
external users and the internal resource are typically secured.
4.2.2 Network Topology
A topology is the characteristic of a communication network that consists of both the physical
configuration of the cabling that is used to inter connect communicating system and the logical way
in which system view the structure of the network. Topology is therefore the physical or logical
arrangement of computers. The following sections explained the different types of network topologies.

Muhammad Aminu Ahmad Page 38


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

Star Topology
This topology consists of a central node to which all other nodes are connected. Star topology is
used in most existing information networks involving data processing and voice communication. This
allows sufficient connection point to be provided for one sub–area, while providing flexibility in their
allocation within that area. Figure 4.1 shows a typical star and extended star topologies.

Figure 4.1: Star and extended star topologies

Advantages of star topology


• Diagnosis and isolation of problem is easy.

• Easy to add a new computer system to the network.

• Failure of one workstation does not affect the entire network.

• Uses a single access protocols.

• Provide ease of service.

• It is very fast.

Disadvantages of star topology


• There is central node dependency.

• Always requires very long cable length when connecting many nodes.

Bus Topology
The bus topology is the simplest method of networking computers. It consists of a single cable known as
a trunk, backbone or segment that connects all the computers in the network. Each system is directly
attached to a common communication channel. Signal that is transmitted over the channel makes
up the messages. As each message passes along the channel, each system receives the message and
examine the destination address contained in the message. If the destination address tells a particular

Muhammad Aminu Ahmad Page 39


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

system that the message is addressed to it, that system accepts and process the message, if the message
address tells the computer that the message is intended for another system, that computer will ignore
the message.
In a bus topology, signals are sent to all the computers in the network. To keep the signal from
bouncing back and forth along the cable, a terminator, British Naval Connector (BNC), is placed at
the end of the cable. In a bus topology only one computer can send data at a time, therefore increasing
number of computers in a bus slows data transmission in the network. A typical bus topology is shown
in Figure 4.2

Figure 4.2: Bus topology

Advantages of Bus topology


• It is cheap, because of its simplicity.

• It requires a short cable length.

• It is easy to expand the network.

• It is easy to set up compared to Star and Ring topologies.

• There is no chances for data collision since only one computer can transmit at a time.

• Locating cable fault in a bus topology is relatively easy.

• Bus topology is ideal for one to many data transmission.

• Signal on the cable are bidirectional, hence reaches all the nodes.

Disadvantages of Bus topology


• Fault diagnosis is difficult in a bus topology – detection of fault may have to be performed from
any point in the network.

• Fault isolation is difficult – if fault in the node is detected, the node can simply be removed. But
if the fault is in the network medium itself, the entire segment of the bus must be disconnected
to isolate the fault.

• Repeater configuration – When a bus type network has its backbone intended for using a repeater,
configuration maybe necessary thus may involve tailoring cable length and adjusting terminator.

• Computer nodes must be intelligence – each node on the network is directly connected to the
central bus. This means that each node must have method of deciding and detecting its own
data.

Muhammad Aminu Ahmad Page 40


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

Ring Topology
In ring topology, each node is connected to form a single closed data path as shown in Figure 4.3.

Figure 4.3: Ring topology

Data from one node are passed along to the next node from which it will be examined, and if that node
is not the intended destination, then it is transmitted to the next node until the destination is reached.
Token (a special bit pattern) is circulated in the network to enable a node to capture the data. Ring
topology might be structured so that there are a number of information frames or slot in construct
circulation. Node wishing to transmit first detects the arrival of an empty slot then inserts the data
it wishes to send and mark the frame as full. The receiving node takes the data and then marks the
frame as empty. In implementation, one particular node has the responsibility for generating the token
or slot when the network is first constituted.
Advantages of ring topology
• The ability to achieve transmission rates of the order of 10 million bits per second.

• Provision of local communication via a single channel.

• No central server, which reduces the cost of establishing the ring topology.

Disadvantages of ring Topology


• Failure of one node result into entire network failure.

• Detection and isolation of fault is very difficult in ring topology.

Tree Topology
The tree topology integrates multiple star topologies together onto a bus. In its simplest form, only
hub devices connect directly to the tree bus and each hub functions as the "root" of a tree of devices.
This bus/star hybrid approach supports future expandability of the network much better than a bus
(limited in the number of devices due to the broadcast traffic it generates) or a star (limited by the
number of hub connection points) alone. A typical tree topology is shown in Figure 4.4.

Muhammad Aminu Ahmad Page 41


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

Figure 4.4: Tree topology

Advantages of a Tree Topology


• Point-to-point wiring for individual segments.

• Supported by several hardware and software vendors.

Disadvantages of a Tree Topology


• Overall length of each segment is limited by the type of cabling used.

• If the backbone line breaks, the entire segment goes down.

• More difficult to configure and wire than other topologies.

Mesh Topology
Mesh topology involves the concept of routes. Unlike each of the previous topologies, messages sent on
a mesh network can take any of several possible paths from source to destination. Some WANs, most
notably the Internet, employ mesh routing. A mesh network in which every device connects to every
other is called a full mesh as shown in Figure 4.5.

Muhammad Aminu Ahmad Page 42


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

Figure 4.5: A mesh topology

4.2.3 Communication Media


Computer networks can be classified according to the hardware and associated software technology
that is used to interconnect the individual devices in the network, such as electrical cable, optical fibre
and radio waves (wireless LAN).
Wired Technologies
The order of the following wired technologies is from slowest to fastest transmission speed.

• Twisted pair wire: This is the most widely used medium for telecommunication. Twisted-pair
cabling consist of copper wires that are twisted into pairs. Ordinary telephone wires consist of
two insulated copper wires twisted into pairs. Computer networking cabling (wired Ethernet
as defined by IEEE 802.3) consists of 4 pairs of copper cabling that can be utilized for both
voice and data transmission. The use of two wires twisted together helps to reduce crosstalk and
electromagnetic induction. The transmission speed ranges from 2 million bits per second to 10
billion bits per second. Twisted pair cabling comes in two forms: unshielded twisted pair (UTP)
and shielded twisted-pair (STP). Each form comes in several category ratings, designed for use
in various scenarios.

• Coaxial cable: This cable consists of copper or aluminium wire surrounded by an insulating
layer (typically a flexible material with a high dielectric constant), which itself is surrounded
by a conductive layer. The insulation helps minimize interference and distortion. Transmission
speed ranges from 200 million bits per second to more than 500 million bits per second.

• ITU-T technology: This uses existing home wiring (coaxial cable, phone lines and power lines)
to create a high-speed (up to 1 Gigabit/s) local area network.

• An optical fibre: This is a glass fibre that uses pulses of light to transmit data. Some advantages
of optical fibres over metal wires are less transmission loss, immunity from electromagnetic
radiation and very fast transmission speed, up to trillions of bits per second. One can use different
colours of lights to increase the number of messages being sent over a fibre optic cable.

Muhammad Aminu Ahmad Page 43


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

Wireless Technologies
• Terrestrial microwave: This uses earth-based transmitters and receivers resembling satellite
dishes. Terrestrial microwaves are in the low-giga hertz range, which limits all communications
to line-of-sight. Relay stations are spaced approximately 48 km apart.

• Communications satellite: This communicates via microwave radio waves, which are not
deflected by the Earth’s atmosphere. The satellites are stationed in space, typically in geo-
synchronous orbit 35,400 km above the equator. These Earth-orbiting systems are capable of
receiving and relaying voice, data and TV signals.

• Cellular systems: These use several radio communications technologies. The systems divide
the region covered into multiple geographic areas. Each area has a low-power transmitter or
radio relay antenna device to relay calls from one area to the next area.

• Radio and spread spectrum technologies: Wireless local area networks use a high-frequency
radio technology similar to digital cellular and a low-frequency radio technology. Wireless LANs
use spread spectrum technology to enable communication between multiple devices in a limited
area. IEEE 802.11 defines a common flavour of open-standards wireless radio-wave technology.

• Infra-red communication: This can transmit signals for small distances, typically no more
than 10 meters. In most cases, line-of-sight propagation is used, which limits the physical
positioning of communicating devices.

• A global area network (GAN): This is a network used for supporting mobile communication
across an arbitrary number of wireless LANs, satellite coverage areas, etc. The key challenge in
mobile communications is handing off user communications from one local coverage area to the
next. In IEEE Project 802, this involves a succession of terrestrial wireless LANs.

4.2.4 Network Devices


Apart from the physical communications media themselves as described above, networks comprise
additional basic hardware building blocks that interconnect their terminals, such as network interface
cards (NICs), hubs, bridges, switches and routers.
Network Interface Cards (NIC)
A network interface card, network card or network adapter, is a piece of computer hardware designed
to allow computers to physically access a networking medium. It provides a low-level addressing system
through the use of media access control (MAC) addresses. Each network interface has a unique MAC
address which is usually stored in a small memory device on the card, allowing any device to connect
to the network without creating an address conflict. Ethernet MAC addresses are composed of six
octets. Uniqueness is maintained by the Institute of Electric and Electronic Engineers (IEEE), which
manages the Ethernet address space by assigning 3-octet prefixes to equipment manufacturers. The
list of prefixes is publicly available. Each manufacturer is then obliged to both use only their assigned
prefix(es) and to uniquely set the 3-octet suffix of every Ethernet interface they produce.

Muhammad Aminu Ahmad Page 44


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

Repeaters and hubs


A repeater is an electronic device that receives a signal, cleans it of unnecessary noise, regenerates it
and retransmits it at a higher power level, or to the other side of an obstruction, so that the signal can
cover longer distances without degradation. In most twisted pair Ethernet configurations, repeaters are
required for cable that runs longer than 100 meters. A repeater with multiple ports is known as a hub.
Repeaters require a small amount of time to regenerate the signal. This can cause a propagation delay
which can affect network communication when there are several repeaters in a row. Many network
architectures limit the number of repeaters that can be used in a row (e.g. Ethernet’s 5-4-3 rule).
Today, repeaters and hubs have been made mostly obsolete by switches.
Bridges
A network bridge connects multiple network segments together. Bridges broadcast to all ports except
the port on which the broadcast was received. However, bridges do not promiscuously copy traffic to
all ports, as hubs do, but learn which MAC addresses are reachable through specific ports. Once the
bridge associates a port and an address, it will send traffic for that address to that port only. Bridges
learn the association of ports and addresses by examining the source address of frames received on
various ports. Once a frame arrives through a port, its source address is stored and the bridge assumes
that MAC address is associated with that port. The first time that a previously unknown destination
address is seen, the bridge will forward the frame to all ports other than the one on which the frame
arrived. Bridges come in three basic types:

• Local bridges: Connect LANs directly.

• Remote bridges: Can be used to create a WAN link between LANs. Remote bridge were largely
replaced by routers, particularly, where the connecting link is slower than the end networks.

• Wireless bridges: Can be used to join LANs or connect remote stations to LANs.

Switches
A network switch is a device that forwards and filters (chunks of data communication) between ports
(connected cables) based on the MAC addresses in the packets. A switch is distinct from a hub in
that it only forwards the frames to the ports involved in the communication rather than all ports
connected. A switch breaks the collision domain but represents itself as a broadcast domain. Switches
make forwarding decisions of frames on the basis of MAC addresses. A switch normally has numerous
ports, facilitating a star topology for devices and cascading additional switches.
Routers
A router is an inter-networking device that forwards packets between networks by processing information
found in the datagram or packet. In many situations, this information is processed in conjunction
with the routing table (also known as forwarding table). Routers use routing tables to determine what
interface to forward packets.

Muhammad Aminu Ahmad Page 45


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

4.2.5 Transmission Modes


A given transmission on a communications channel between two machines can occur in several different
ways. The transmission is characterized by:

• The direction of the exchange.

• The number of bits sent at a time.

• Channel; synchronous and asynchronous.

Direction of the Exchange


There are three different transmission modes characterised according to the direction of the exchanges:

• A simplex connection is a connection in which the data flow in only one direction, from the
transmitter to the receiver. This type of connection is useful if the data do not need to flow
in both directions (for example, from your computer to the printer or from the mouse to your
computer).

• A half-duplex connection (sometimes called an alternating connection or semi-duplex) is a


connection in which the data flow in one direction or the other, but not both at the same
time. With this type of connection, each end of the connection transmits in turn. This type of
connection makes it possible to have bidirectional communications using the full capacity of the
line.

• A full-duplex connection is a connection in which the data flow in both directions simultaneously.
Each end of the line can thus transmit and receive at the same time, which means that the
bandwidth is divided into two for each direction of data transmission if the same transmission
medium is used for both directions of transmission.

Number of Bits Transmitted


The transmission mode refers to the number of elementary units of information (bits) that can be
simultaneously translated by the communications channel. In fact, processors (and therefore computers
in general) never process (in the case of recent processors) a single bit at a time; generally they are
able to process several bits, and for this reason the basic connections on a computer are parallel and
serial connections.

• Parallel connection: This means simultaneous transmission of N bits. These bits are sent
simultaneously over M different channels (a channel being, for example, a wire, a cable or any
other physical medium). The parallel connection on PC-type computers generally requires 10
wires. These channels may be:

– A number of physical lines in which case each bit is sent on a physical line (which is why
parallel cables are made up of several wires in a ribbon cable).

Muhammad Aminu Ahmad Page 46


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

– One physical line divided into several sub-channels by dividing up the bandwidth. In this
case, each bit is sent at a different frequency. Since the conductive wires are close to each
other in the ribbon cable, interference can occur (particularly at high speeds) and degrade
the signal quality.

• Serial connection: In a serial connection, the data are sent one bit at a time over the transmission
channel. However, since most processors process data in parallel, the transmitter needs to
transform incoming parallel data into serial data and the receiver needs to do the opposite.
These operations are performed by a communications controller, normally a UART (Universal
Asynchronous Receiver Transmitter) chip.

Transmission Channel
• In asynchronous connection, each character is sent at irregular intervals in time (for example a
user sending characters entered at the keyboard in real time). So, for example, imagine that a
single bit is transmitted during a long period of silence; the receiver will not be able to know if this
is 00010000, 10000000 or 00000100. To remedy this problem, each character is preceded by some
information indicating the start of character transmission (the transmission start information
is called a START bit) and ends by sending end-of-transmission information (called STOP bit,
there may even be several STOP bits).

• In a synchronous connection, the transmitter and receiver are paced by the same clock. The
receiver continuously receives (even when no bits are transmitted) the information at the same
rate the transmitter sends it. This is why the transmitter and receiver are paced at the same
speed. In addition, supplementary information is inserted to guarantee that there are no errors
during transmission. During synchronous transmission, the bits are sent successively with no
separation between each character, so it is necessary to insert synchronization elements; this is
called character-level synchronization. The main disadvantage of synchronous transmission is
recognizing the data at the receiver, as there may be differences between the transmitter and
receiver clocks. That is why each data transmission must be sustained long enough for the receiver
to distinguish it. As a result, the transmission speed cannot be very high in a synchronous link.

4.3 The Internet


The Internet is a global system of interconnected governmental, academic, corporate, public and private
computer networks. The Internet is a medium of sharing information globally with ease and speed.
In this digital age, more and more of what we do is somehow related to the Internet; job application,
business and marketing, education, communication, etc. The Internet is a global interconnected
network of millions of computers together. Information that travels over the Internet does so via a
variety of languages known as protocols. The Internet is a cooperative endeavour—no organization is
in charge of the Internet. The Internet is based on the networking technologies of the Internet Protocol
Suite. Every computer in the Internet is identified by a unique IP address. The Internet is accessible
to every user all over the world.

Muhammad Aminu Ahmad Page 47


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

4.3.1 Internet Evolution


The concept of Internet originated in 1969 and has undergone several technological and infrastructural
changes. The Internet originated from the Advanced Research Projects Agency Network (ARPANET).
ARPANET was developed by DARPA of the United States Department of Defense. The purpose of
ARPANET was to provide communication among the various bodies of government. In 1972, the
ARPANET spread over the globe with 23 nodes located at different countries and thus became known
as Internet. As the Internet grew, it was used for applications beyond research, such as electronic mail.
In the early 1980s, the current versions of the core Internet protocols, TCP and IP, were introduced. In
1991, the Center for European Nuclear Research (CERN) released the first versions of World Wide Web
(WWW) software. The invention of new technologies such as Transmission Control Protocol/Internet
Protocol (TCP/IP), WWW, domain name system (DNS), browsers, scripting languages etc., provided
a medium to publish and access information over the web.
4.3.2 Internet Layered Architecture
The Internet consists of four layers as presented in Figure 4.6; application, transport, internet and
host-to-network layers.

Figure 4.6: Internet Layered Architecture

Application layer
It provides different services such as manipulation of information in several ways, re-transferring of
information, distribution of information, etc. The functions such as LOGIN or password checking are
also performed by the application layer. Protocols used in the layer comprises FTP, HTTP, NNTP,
SMTP and Telnet.

• Transfer Protocol (FTP): This protocol is used to copy files from one host to another in the
following manner:

– Creates two processes such as control process and data transfer process at both ends, that
is, at client and server sides.
– Establishes two different connections: one is for data transfer and other is for control
information.
– Uses port 21 for the control connection and Port 20 for the data connection.

Muhammad Aminu Ahmad Page 48


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

• Hyper Text Transfer Protocol (HTTP): This protocol is used for communication. It defines
mechanism for communication between browser and the web server. It is also called request and
response protocol because the communication between browser and server takes place in request
and response pairs.

• Net News Transfer Protocol (NNTP): This protocol is used to access or transfer Usenet news
over the Internet.

• Simple Mail Transfer Protocol (SMTP): This protocol is used for sending e-mails efficiently
and reliably over the Internet. It handles exchange of messages between e-mail servers over
TCP/IP network. Apart from transferring e-mail, SMTP also provides notification regarding
incoming mail. When you send an e-mail, your e-mail client sends it to your e-mail server which
further contacts the recipient mail server using SMTP client. These SMTP commands specify
the sender’s and receiver’s e-mail address, along with the message to be send. The exchange of
commands between servers is carried out without intervention of any user. If messages cannot be
delivered, an error report is sent to the sender which makes SMTP a reliable protocol.

• Telnet: This protocol is used to log in to a remote computer on the Internet. There are a number
of Telnet clients having user friendly interface.

Transport Layer
The transport layer performs the following functions:

• It decides if the data transmission should take place on parallel paths or single path.

• It performs multiplexing and splitting of the data.

• It breaks the data groups into smaller units so that they are handled more efficiently by the
network layer.

The transport layer guarantees transmission of data from one end to another. The transport layer
uses TCP and UDP protocols for end to end transmission. TCP is a reliable and connection oriented
protocol. TCP provides means to allow two software on difference machines on the Internet find each
other, rendezvous and transfer data. TCP also provides an essential service of making sure that each
piece of data is transferred in the correct sequence and without error. TCP also handles flow control.
The UDP is a connection less protocol. It is not reliable and does not perform flow control.
Internet Layer
The function of this layer is to allow the host to insert packets into network and then make them travel
independently to the destination. However, the order of receiving the packet can be different from the
sequence they were sent. The Internet layer used Internet Protocol (IP) for addressing.

Muhammad Aminu Ahmad Page 49


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

Host-to-Network
This is the lowest layer in the Internet model. The host has to connect to network using some protocols,
so that it can send IP packets. This protocol varies from host to host and network to network. Some
of the protocols used are ARPANET, Ethernet and packet radio.
4.3.3 Internet Design Principles
The fundamental design principles of the Internet are interoperability, layering, simplicity, uniform
naming and addressing and end-to-end protocol.
Interoperability
Interoperability means that systems can be assembled using client and server computers and software
from different vendors. In the context of Internet commerce, interoperability means that buyers and
sellers do not have to buy and upgrade software simultaneously from the same vendors to conduct
commerce. Thus, independent implementations of Internet protocols work together.
Layering
Internet protocols are designed to work in layers, with each higher layer building on the facilities
provided by lower layers.
Simplicity
The layering of the Internet grows both up and down from Internet Protocol. Internet Protocol
(IP) is very simple and provides only addressing and formatting of packets. Below the level of IP,
there is the complexity of many different kinds of network hardware, topologies and routers. IP
hides that complexity from applications and insulates application developers from the complexities of
different network devices and the complexities of implementing low-level network protocols. Above IP,
higher-level protocols such as TCP offer service abstractions that are easy for application programmers
to understand and use.
Uniform Naming and Addressing
The IP layer offers a uniform addressing structure that assigns a 32-bit address to each computer
connected to the network known as IP Address. IP address is a unique set of numbers such as
10.23.33.114, which identifies a computer location. Domain name system offers a uniform way to
translate human-readable names for computers, such as www.google.com to the numeric address for
that computer. The domain name system comprises domain names, domain name space and name
server.

• Domain Names: Domain name is a symbolic string associated with an IP address. There are
several domain names available; some of them are generic such as com, edu, gov, net etc, while
some are country level domain names such as au, in, ng, za, us etc. Table 4.1 shows the some
generic top-level and country top-level domain names.

• Domain Name Space: The domain name space refers to a hierarchy in the Internet naming
structure. This hierarchy has multiple levels from 0 to 127, with a root at the top. Figure 4.7

Muhammad Aminu Ahmad Page 50


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

Table 4.1: Generic and Country Top-Level Domain Names


Domain Name Meaning Domain Name Meaning
Generic Top-Level Domain Names Country Top-Level Domain Names
com Commercial business ca Canada
edu Education in India
gov U.S. government agency jp Japan
int International entity ng Nigeria
mil U.S. military uk United Kingdom
net Networking organization us United State
org Non profit organization za South Africa

shows the domain name space hierarchy.

com gov ng org

google Yahoo edu org

abu buk kasu

acc csc

Figure 4.7: Domain Name Space Hierarchy

Each subtree in Figure 4.7 represents a domain. Each domain can be partitioned into sub domains
and these can be further partitioned and so on. For example, the top-level domain for Nigeria is
“ng”, which is further partitioned into “edu” and “org” domains for educational institutions and
Nigerian government agencies respectively. The domain for educational institutions comprises

Muhammad Aminu Ahmad Page 51


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

“abu”, “buk” and “kasu” for domains Ahmadu Bello University, Bayero University Kano and
Kaduna State University respectively. The “kasu” domain comprises the “acc” and “csc” domains
for accounting and computer science departments respectively.

• Name Server: Name server contains the DNS database. This database comprises various names
and their corresponding IP addresses. Since it is not possible for a single server to maintain entire
DNS database, the information is distributed among many DNS servers. The server maintains
a database called zone file for every zone. Zone is a collection of sub-domains under the main
domain.

End-to-End
The Internet is designed around end-to-end protocols; the interpretation of the data happens on the
sending and receiving systems, but nothing in the network needs to look at anything but the destination
address for delivering the packet. End-to-end protocols have several advantages such as hiding the
internal structure of the network and providing simple abstractions to programmers; shielding them
from details of recovering from lower-level errors.
4.3.4 Internet Applications
The Internet is now the biggest network of resources and provides a wide variety of services such as
electronic mail, file transfer, interest group membership, interactive collaboration, multimedia displays,
real-time broadcasting, shopping opportunities, and much more. Some of the common services provided
by the Internet are presented in the following sections:
The World Wide Web (WWW)
The World Wide Web is a way of accessing information in the Internet. The World Wide Web was
created by Timothy Berners Lee in 1989 at CERN in Geneva. The World Wide Web came into existence
as a proposal to allow researchers to work together effectively and efficiently at CERN. Eventually
it became World Wide Web. The WWW project merges the techniques of network information and
hypertext to make an easy but powerful global information system.
The web uses the HTTP protocol (hypertext transfer protocol), which is only one of the many
“languages” spoken over the Internet, to transmit data. HTTP is a simple data transfer protocol that
binds the web together and supports the communications between a web client (browser) and its web
server. HTTP consists of a set of messages and replies for both servers and browsers and relies on the
Universal resource identifier (URI), enclosed in the universal resource locator (URL), to identify files.
The web utilizes special software called browsers to access web documents (more commonly known as
web pages) that are linked to each other via hyperlinks. Web pages contain some or all of the following:
text, images, audio and video.
A web browser is used as a client on the web to support users requests, connect to a web server
using URL information, format and display the responding information (from the web server). A web
server listens for incoming requests from a web browser to find the requested document and transmit
information to the browser or find a program and execute it. A URL is the address of web resource

Muhammad Aminu Ahmad Page 52


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

that leads to a file, a single record in a database, the front-end of an Internet program or a result of a
query. Example

http://www.kasu.edu.ng/

The http:// enables a web browser to locate and display the web page or website. Most browsers
will automatically add this prefix. The www stands for world wide web. This means that the page is
somewhere on the world wide web. For some websites, it is not necessary to type in the “www” part.
The text “kasu” is the name of the web page or website (or the host). It is flanked by dots on either
side which separate it from other sections of the web address. The edu.ng is the top level domain
name for educational institutions in Nigeria. This indicates where the web page is registered, and often
tells what kind of website it is.
The WWW works on client-server approach using the following steps:

• User enters the URL (example http://www.google.com) of a web page in the address bar of a
web browser.

• Then the browser send a request to the domain name server for the IP address corresponding to
www.google.com.

• After receiving the IP address, the browser sends the request for web page to the web server
using the HTTP protocol, which specifies the way the browser and web server communicates.

• Then web server receives request using HTTP protocol and searches for the requested web page.
If found it returns it back to the web browser and closes the HTTP connection.

• Now the web browser receives the web page, interprets it and display the contents of web page in
web browser’s window.

A website is a collection of web pages that can be identified using a domain name. Websites can be
accessible to the whole world via the Internet, or can be a private affair available only to users in an
organization. There are private and public websites. Private websites are called Intranet servers, which
are used by internal users in an organization. Private websites are set-up inside a firewall to protect
access from external users, but shared by all internal users across many types of local area TCP/IP
based computer network. Public websites are accessible by users through the Internet. Public websites
are normally placed on a web server that has Internet connection, which is maintained by the owner of
the website or an organisation that provides web hosting services.
There are advantages and disadvantages in setting up a web server by an organisation to host a
website or having a website hosted by a web hosting organisation. Setting up a web server within an
organisation provides complete control over the operations of the server and ability to use server scripts
that interact with other systems in the organisation. However, the organisation needs to connect the
web server to the Internet and provide an administrator for the web server. On the other hand, having
a website hosted by a web hosting organisation relieves an organisation from the need for a high speed
Internet connection, hardware and software to set up a web server. However, the website must be

Muhammad Aminu Ahmad Page 53


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

managed remotely and the owner of the website will give up the ability to write server scripts and
integrate the website with other system.
Search Engines
Search engine refers to a huge database of Internet resources such as web pages, newsgroups, programs,
images etc. It enables users to locate information on World Wide Web. Users can search for any
information by passing a query in form of keywords or a phrase. It then searches for relevant information
in its database and return to the user. There are three basic components of a search engine; web
crawler, database and search interfaces.
The web crawler is a software component that traverses the web to gather information. Information
on the web is stored in database, which consists of huge web resources. Search interface is the component
that resides between a user and the database. It helps the user to search through the database. The
web crawler, database and search interface components make the search engine work. Search engines
make use of Boolean expression AND, OR and NOT to restrict and widen the results of a search. To
search for a web resource, the following are the steps are performed by a search engine:

• The search engine looks for the keyword in the index for predefined database instead of going
directly to the web to search for the keyword.

• The search engine then uses the web crawler to search for the information in the database.

• Once web crawler finds the pages, the search engine then shows the relevant web pages as a
result, which include title of the pages, size of text portion, first several sentences etc. The
search criteria may vary from one search engine to the other. The retrieved information is ranked
according to various factors such as frequency of keywords, relevancy of information, links etc.

• A user can then select any of the search results to open the web resource using a web browser.

Electronic Mail
Electronic mail, or e-mail, is a fast, easy and inexpensive way to communicate with other Internet
users around the world. It is one of the basic and earliest services of the Internet and the most used
application on the Internet too. E-mail overcomes most of the problems and delays of getting a physical
document from one person to another. Rather, it has the dual advantage of being faster
File Transfer Protocol (FTP)
The FTP is a system of rules and a software program that enables a user to log on to another computer
and transfer information between the two computers. It was the first service developed for the Internet
so that government and educational institutions could easily exchange files. FTP allows the user to
get access to the files stored in the directory of a remote computer that is connected to the Internet.
Using FTP, a user can upload and download files from the remote computer (known as FTP servers),
with access permission on the remote machine.

Muhammad Aminu Ahmad Page 54


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

Telnet
Telnet is a protocol that allows a user to log on to a remote computer. Telnet is also known as remote
login, which means connecting one machine to another in such a way that a person may interact with
another machine as if it is being used locally.
Internet Relay Chat (IRC)
The IRC is a service on the Internet that allows people to communicate in real time and carry on
conversations via the computer with one or more people. It provides the user with the facility to
engage in simultaneous (synchronous) online conversation with other users from anywhere in the world.
Chatting and Instant Messaging
Chart programs allow users on the Internet to communicate with each other by typing in real time.
They are sometimes included as a feature of a website, where users can log into chat rooms to exchange
comments and information about the topics addressed on the site.
Internet Telephony
Internet telephone is the use of the Internet rather than the traditional telephone company infrastructure,
to exchange spoken or other telephonic information. It consists of hardware and software that enable
people to use the Internet as a transmission medium for telephone calls. There are many Internet
telephony applications available. Some, Internet telephony applications such as Cool Talk and
NetMeeting, come bundled with popular web browsers.
Video Conferencing
Video conferencing uses the same technology as IRC, but also provides sound and video pictures. It
enables direct face-to-face communication across networks. A video conferencing system has two or
more parties in different locations, which have the ability to communicate using a combination of video,
audio and data. A video conference can be person to person (referred to as “point-to-point”) or can
involve more than two people (referred to as “multipoint”) and the video conferencing terminals are
often referred to as “endpoints”.
Newsgroups (Usenet)
Newsgroups are international discussion groups that focus on a particular topic and help in gathering
information about the topic. The information or articles that make up the “news” are written by
people interested in a specific topic. These articles are posted to the newsgroup so that others can
read, reply and comment on them.
Mailing Lists (List server)
The Internet is a home to a large community of individuals who carry out active discussions, organized
around topic-oriented forums that are distributed via e-mail. This method of Internet communications is
known as mailing list and it enables people with similar interests from all over the world to communicate
and share information with each other.

Muhammad Aminu Ahmad Page 55


Chapter
5
Applications of Computers

5.1 Introduction
Computers play a very important role in almost every aspect of human life; banking, insurance,
transportation, communication, etc. Computers are useful in data processing, resource sharing and
communication as previously discussed. The use of computers in data processing and other activities
includes office automation, business transactions, financial transactions, scientific computing and
engineering design. This shows how computers are used to solve problems or achieve a desired activity.
This chapter discusses some applications of computers in facilitating activities and solving different
problems.

5.2 Office Automation System


The introduction of mini computers significantly changed the way work is done in offices. Office
automation is a collection of computer-based office-oriented technologies with the basic objective of
improving the efficiency of office work.
Document Management System
A document management system comprises applications that are used to create and manipulate
documents such as word processing, desktop publishing, spreadsheets and image processing.

• Word processing: This is used to create document electronically such as letters, proposals, reports
and brochures. It allows manipulation of such documents and their storage and retrieval.

• Spreadsheet: This is used to maintain records and perform calculations such as expenses, profits
and losses. It is used to perform mathematical, statistical and logical processing.

• Desktop publishing: This is used to produce professional print quality documents with photos
and graphics. A user can combine text, artwork, photos and a variety of fonts to produce the
document.

56
Kaduna State University CSC101 Lecture Note: 2017-2018 Session

• Multimedia processing: This is used to manipulate and store images, audio and video in a
computer. It can also be used to improve the quality of images, audio and videos.

Payroll System
Organisations employ people for their businesses, management and other activities. The employees
have to be paid their salaries periodically either weekly or monthly. Therefore the payment details of
employees in an organisation have to be processed and stored. Computer facilitates the process using a
computer program that consists of a number of smaller programs or modules. Each module performs a
particular function of the payroll. This set of programs is called a payroll system.
To calculate the pay of an employee, organisations normally use employee number (a unique number
assigned to an employee), name, basic pay, allowances, deductions and bank account number. Using
a payroll system, the details of the employees are stored permanently in a master file in a computer
storage. For example, if an employee completes a year of service, he normally gets an increment. This
is updated using the master update module of the payroll system. Another module of the payroll
system reads details from master file and calculates net pay. The program also prints out pay slip for
each employee. A pay slip shows the employee number, name, basic pay, various allowances, various
deductions and net pay. The payroll system also generates a number of statements.
Office Support System
This is a collection of programs that are used to coordinate the activities of a workgroup in an
organisation. The members of a work-group can use the system to collaborate and exchange information
irrespective of their location. Examples of groupware applications are Lotus Notes and Microsoft
SharePoint and Exchange. Most of the groupware applications include calendering and scheduling,
discussion databases, reference library and messaging.
Data Management System
This is used to effectively organise, manipulate and store records. Educational organisations use
data management system to manage employee and student records. In addition to employee records,
hospitals use data management system to keep the records of patients, medicines and prescriptions.
Communication Systems
These are used to send messages, documents, images, audio and videos from one location to another.
These programs includes facsimile (Fax), email and Teleconference.

5.3 Business
Computers have tremendously improved the way businesses operate in their respective industries.
Businesses that do not use computers are at a major disadvantage against their competitors. The
following are some of the applications of computers in businesses.
Transaction Processing System
Transaction Processing Systems (TPS) are among the earliest computerised systems catering to the
requirements of large business enterprises. The purpose of a typical TPS is to record, process, validate

Muhammad Aminu Ahmad Page 57


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

and store transactions that occur in the various functional areas of a business for subsequent retrieval
and usage. A transaction could be internal or external. When a department requisitions material
supplies from stores, an internal transaction is said to have occurred. However, when the purchase
department purchases materials from a supplier, an external transaction takes place. The steps involved
in TPS are data entry, data validation, processing and revalidation, storage and reporting.
Order Processing System
Companies often use a set of processes to complete the tasks and activities that occur in their businesses
every day. Order processing is one of these activities. An order processing system captures order data
from customer service employees or from customers directly, stores the data in a central database and
sends order information to the accounting and shipping departments, if applicable. Order processing
systems provide tracking data on orders and inventory for every step of the way.
Inventory Control System
Computers are used to keep track of purchases and raw materials needed in an organization. The
purchases and raw materials are called inventories and the set of programs used to keep track of these
inventories constitute the inventory control system. Therefore, a particularly quantity of each item or
raw material has to be stocked. An inventory control system helps in planning and control functions of
inventory management.
The inventory control system maintains a file with item number, name, quantity on stock a company
orders and the suppliers’ addresses. This file is the inventory master. When an item is issued, the
inventory update program updates the inventory master reducing the stock by the quantity issued. If
the resultant stock falls below the reorder level, the inventory control program prints out an order
to the supplier of the item automatically. It can also be mailed to the supplier. When the supplier
supplies the item, the inventory control program updates the stock. The inventory control system can
quickly inform the management of a company on the usage of items over a period of time. It also
maintains an optimum level of stock of these items.
Decision Support System
A decision support system is a computer application that helps users in analysing problems and
making business decisions more confidently. It uses data routinely collected in organizations and special
analysis tools to provide information support to complex decisions. For example, a sales department
of a company may be interested in analysing various sales decision options. The decision support
application might gather data, present the data graphically and help in evaluating various options. It
may use past sales figures, project sales based on sales assumptions for each alternative considered and
display information graphically. It may also use artificial intelligence to enhance its decision support
capability.
Electronic Commerce
Electronic commerce is the process of searching, choosing, buying and selling of product or service on
the electronic network; it uses the computer and communication networks for promoting products,

Muhammad Aminu Ahmad Page 58


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

selling, delivery, collection and delivery service. In e-commerce, the parties to a transaction interact
electronically. They may be separated by long distances physically, yet the electronic network brings
them together not only to complete a transaction but also to get sales support. The most important
advantage of the internet for business firms is that it allows reaching customers at very low costs.

5.4 Banking and Finance


The following are the major impacts of the use of computers in banking and finance:
Automated Teller Machine (ATM)
An ATM is a device uses computers to enable a customer perform financial transactions using a
personal identification number. This enabled an ATM to dispense cash at any time of the day and
night, unlike the traditional method where customers have to queue in a bank for a very long time in
order to withdraw cash or transfer funds. To use an ATM, a customer is issued an ATM card. This is
a plastic card, which bears the customer’s name. This card is magnetically coded and can be read by
the ATM machine. Each card holder is provided with a secret personal identification number (PIN).
When the customer wants to use the card, he has to insert his plastic card in the slot of the machine.
After the card is a recognized by the machine, the customer enters his personal identification number.
After establishing the authentication of the customers, the ATM machine allows the customer to do
the desired transaction. When the transaction is completed, the ATM ejects the customer’s card.
Telephone Banking
Telephone banking provides a 24 hour banking facility to customers. Telephone banking is based on
the voice processing facility available that is controlled using computers. The caller usually a customer
calls the bank any time and can enquire balance in his account or other transaction history. In this
system, the computers at the bank are connected to a telephone link with the help of a modem. Voice
processing facility is provided in the software. The software identifies the voice of caller and provides
him suitable reply.
Internet Banking
Internet banking enables a customer to do banking transactions through the bank’s website on the
Internet. It is a system of accessing accounts and general information on bank products and services
through a computer. This is more or less bringing the bank to your computer. In traditional banking,
a customer has to approach the branch in person to withdraw cash or deposit a cheque or request a
statement of accounts etc. However, Internet banking has changed the way of banking now, because a
customer can do transactions using a computer through the website of a bank. All such transactions
are encrypted using computer software. A customer can be rest assured that transactions are secure
and confidential.
Bankers Automated Clearing Services
This involves the use of Magnetic Ink Character Reader (MICR) for cheque processing. It is capable
of encoding, reading and sorting cheques. Also, request for cheque books or purchase of draft can be
made and granted via electronic devices.

Muhammad Aminu Ahmad Page 59


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

Accounting Information System


Accounting software is used to implement a computerised accounting system. The computerised
accounting system is based on the concept of databases. It does away with the concept of creating and
maintaining journals, ledger, etc., which are essential while working with manual accounting system. A
computerised accounting system offers the following features:

• Online input and storage of accounting data.

• Print out of purchase and sales invoices.

• Logical scheme for codification of accounts and transactions. Every account and transaction is
assigned a unique code.

• Grouping of accounts is done from the very beginning.

• Instant reports for management, for example – Statement, Trial Balance, Trading and Profit
and Loss Account, Balance Sheet, Stock Valuation, Value Added Tax (VAT), Returns, Payroll
Report, etc.

Accounting Information System (AIS) identifies, collects, processes and communicates economic
information about an entity to a wide variety of users. Such information is organised in a manner that
correct decisions can be based on it.

5.5 Computational Science


Computational science (also known as scientific computing) is a collection of tools, techniques and
theories required to solve complex problems in science and engineering using computers. Majority of
these tools, techniques and theories were originally developed in Mathematics before the advent of
electronic computers. This set of mathematical theories and techniques is called Numerical Analysis
(or Numerical Mathematics) and constitutes a major part of computational science. The development
of the electronic computer, however, signalled a new era in the approach to the solution of scientific
problems.
Many numerical methods that had been developed for the purpose of hand calculation (including
the use of desk calculators for the actual arithmetic) had to be revised. Considerations that where
irrelevant or unimportant for hand calculation now became of utmost importance for the efficient
and correct use of a large computer system. Many of these considerations – programming languages,
operating systems, management of large quantities of data, correctness of programs – were subsumed
under the new discipline of Computer Science, on which scientific computing now depends heavily.
In summary, scientific computing draws on mathematics and computer science to develop the best
way to use computer systems to solve problems from science and engineering. Computational biology,
computation chemistry, computational engineering, computation mathematics and computational
physics are sub-fields of computational science.

Muhammad Aminu Ahmad Page 60


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

5.6 Education
Computers have become essential in education and teaching. The use of multimedia packages, hypertext
video chats, web based education, multimedia based education, intelligent tutoring system, digital
libraries, simulation laboratories, tele-education find their places in education. The use of computers in
imparting education to student has been found attractive and satisfying. Some of the uses of computers
in education includes CAL, CAI, distance learning, digital libraries and e-learning.
Computer Aided Learning (CAL)
Computer Aided Learning is an interactive technology that describes an educational environment
where a computer program is used to assist people in learning a particular area of study. CAL refers
to an overall integrated approach of instrumental methods. CAL is a device/learning strategy to make
teaching more interesting and sustainable. CAL is becoming an important part of education system.
CAL system has its own vital merits as follows;

• Well organized and readily accessible information to user.

• Allows users to work privately and without any interference.

• Elegant way to present information through graphics and animation.

• Rapid response to user’s queries.

• Overcomes traditional approach of blackboard and most of times one way communication.

• User satisfaction can be achieved as it can be used multiple times.

• It is convenient as it can be used at home or work place.

• It is dynamic because its content can be easily modified and upgraded depending upon current
information.

• It is self-evaluating, resource effective, dependable, simulative and numerically judicious.

Computer Aided Instruction (CAI)


Computer Aided Instruction is a strategy of delivering learning objectives using computer-based tools
and applications such as electronic lecture halls and electronic seminar rooms in a university for
multimedia supported lectures, the use of projector in lecture halls and the use of an interactive
white board. There is also video conference system for live conversations with external discussions
transmitted into lecture hall. Video conferences can be used to transfer lectures to another venue
within the same university or other universities, thereby increasing the inter university cooperation with
live video conference between two lecturers on the same subject in different universities. Computers
also find their place in classrooms for the purpose of presenting graphics, animation and attractive
presentation, which allows easy understanding for the student.

Muhammad Aminu Ahmad Page 61


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

E-learning
E-learning is commonly referred to the intentional use of networked information and communications
technology in teaching and learning. A number of other terms are also applied to e-learning like online
learning, virtual learning, distributed learning, network and web-based learning. There are four basic
models for e-learning:

• Individualized self-paced e-learning online: This refers to situations where an individual


learner is accessing learning resources such as a database or course content online via an Intranet.
A typical example of this is a learner studying alone or conducting some research on the Internet
or a local network.

• Individualized self-paced e-learning offline: This refers to situations where an individual


learner is using learning resources such as a database or a computer-assisted learning package
offline (while not connected to an Intranet). An example of this is a learner working alone off a
hard drive, a CD or DVD.

• Group-based e-learning synchronously: This refers to situations where groups of learners


are working together in real time through the Intranet. It may include text-based conferencing,
and one or two-way audio and video conferencing. Examples of this include learners engaged in a
real-time chat or an audio-video conference.

• Group-based e-learning asynchronously: This refers to situations where groups of learners


are working over an Intranet, where exchanges among participants occur with a time delay (not
in real time). Typical examples of this kind of activity include on-line discussions via electronic
mailing lists and text-based conferencing within learning managements systems.

Distance Learning
Distance education is usually defined as education that takes place when distance or technology
separates the teacher and the learner. The education modes are print correspondence, audio graphics,
instrumental television, videotape, teleconferencing and a computer conferencing. Choosing a mode
depends on educational need or goal. It may be divided as asynchronous or static education, and
synchronous or dynamic (real-time) distance education.

• Asynchronous or static distance education: This means that students and instructors are
not required to be present at the same time. Students do not have to be gathered together in the
same location at the same time. Rather, they may choose their own instructional time frame and
gather learning materials according to their schedules. Delivery modes of asynchronous distance
education include email, video/audio tapes, web pages, CD-ROMs, fax and traditional postal
mail.

• Synchronous distance education: This includes the use of satellite video conference, desktop
video conference and multi-user domain object-oriented (MOO). Satellite video conference is
usually a one-way video and a one-way audio with a telephone number available for questions.

Muhammad Aminu Ahmad Page 62


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

Satellite video conference is used to cover mass education. Desktop video conferences may
be a one-way video and a two-way audio or a two-way video and audio. Video conferencing
technology is used to simulate a classroom environment for distance learners. The system
supports spontaneous interactive lectures, question and answer sessions and discussions with the
students. Multi-user domain Object-Oriented (MOO) allows users to connect from anywhere in
the world and enables them to communicate with others in real time (as opposed to the delayed
communication of email). Instructors may use a Web interface over the MOO to interact with
their participants. Courses delivered over the MOO require less overhead cost than those via
video conferences.

Digital Libraries
Digital libraries are an electronic collection of real or virtual resources that are available online or offline
anywhere in the world . They have become widely accepted and even preferred information sources
in areas of education, science and others. The speedy expansion of the Internet and the increasing
interest in development of digital library related technologies and collections helped to speed up the
digitization of printed documents in the past few years. Advantages of digital libraries includes;

• Minimizing storage space.

• Cutting down the cost of library maintenance and resource distribution.

• Information that cannot be provided in printed format can be presented using audio and videos.

• Easy for distribution via the Internet, compact disk (CD) and digital versatile disk (DVD).

• Less time required for searching.

• Multiple access.

Publication
Publication of research work is an important aspect in any field of study and a vital element of
researcher’s profession. The use of computers in writing and editing makes it very effortless and
versatile to prepare and publish article. Computers may be required at the different stages for the
author, publisher and reviewer. For writing paper, word processing applications are used, which are
available on a computer and easy to operate. Word processing applications provide numerous tools
for typing and processing options for documents such as spell check correcting grammatical mistake,
providing option for inserting tables of required size, graphics, footnotes and many more.
When it comes to publishing articles, conventional ways are very tedious and time consuming.
But using computers and the Internet makes it very easy. The Internet can be used to search for a
list of different journals, their guidelines for writing research paper and submission process. Most
journals today offer the opportunity to submit paper through their websites, which is called “electronic
submission” or “e-submission”. E-submission is a faster mode of submitting paper by just one click.
Publishers can also send back articles to the author for corrections by e-mail.

Muhammad Aminu Ahmad Page 63


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

5.7 Engineering Design


Computer Aided Design (CAD) is the use of computer system in design process. A CAD system
consists of computer hardware, specialised software and peripherals. The role of the CAD is aiding a
designer to

• Accurately generate and easily modify graphical representation of a product. The user can view
the actual product on screen, make any modifications to it, and present ideas on screen without
any prototype, especially during the early stages of the design process.

• Perform complex design analysis in short time and implementing finite elements analysis methods.

• Perform static, dynamic and natural frequency analysis, heat transfer analysis, plastic analysis,
fluid flow analysis, motion analysis, tolerance analysis and design optimisation.

• Record and recall information with consistency and speed. In particular, the use of Product
Data Management (PDM) systems can store the whole design and processing history of a certain
product for future reuse and upgrade.

CAD is one of the most popular computer tools used by engineers. CAD helps engineers create designs,
analyse equipment and optimize engineering processes. Computers use CAD software to analyse how
certain conditions may affect the engineer’s design and understand which safety precautions may be
necessary for different processes. For example, an engineer may use software to simulate how a bridge
would hold up under stress from inclement weather, earthquakes or heavy traffic. Engineers may then
use these results to make decisions and develop solutions to any problem that arise.

5.8 Expert Systems


An expert system gathers together a database of knowledge or expertise to offer advice or solution
for problems in a particular area by emulating the abilities and judgements of human experts. It
accumulates all the expert knowledge in a given area so that the advice or solution offered is better
than that of a single consultant or expert. It guides users through problems by asking them a set of
questions about the problem. The answers given are checked against the rule base in the system to
draw appropriate conclusions from the problem situation. Expert systems are particularly useful in
dealing with unstructured problems.
Developing an expert system involves extracting relevant knowledge from human experts in the area
of problem, called domain experts. Such knowledge is often heuristic in nature, i.e., useful knowledge
based on some “rules of thump” rather than absolute certainties. Acquisition of such rules of thump
and storing them in knowledge base are serious tasks in building a knowledge base. The expert system
consists of two major parts: the development environment and the consultation environment. The
expert system builder uses the development environment to build the components and stores expertise
into the knowledge base. Non-expert users use the consultation environment to get the expert opinion
and advice from the expert system.

Muhammad Aminu Ahmad Page 64


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

5.9 Geographic Information System (GIS)


Geographic information system is a computer-based system that acquires spatial data from a variety
of sources, changes the data into useful formats, stores the data, and retrieves and manipulates the
data for analysis. GIS is a computer software that links geographic information (where things are)
with descriptive information (what things are). GIS shows data on a map such as streets, buildings
and vegetations, which enables people to analyse and understand patterns and relationships.
With GIS technology, people can compare the locations of different things in order to discover how
they relate to each other. For example, using GIS, a single map could include sites that produce
pollution, such as factories, and sites that are sensitive to pollution, such as wetlands and rivers. Such
a map would help people determine where water supplies are most at risk. GIS applications include
both hardware and software systems. These applications may include cartographic data, photographic
data, digital data or data in spreadsheets.

5.10 Health
Health care institution employ computer systems to maintain patient records. It is often necessary to
maintain detailed records of the medical history of patients. Doctors often require the information
about a patient’s family history, physical ailments, already diagnosed diseases and prescribed medicines.
This information can be effectively stored in a computer database. Applications of computers in health
also include medical equipments, electronic medical record and telemedicine, pharmaceutical analysis,
computer aided drug design, clinical trials, pharmacokinetics and pharmacy robots for dispensing
prescriptions.
Medical Equipment and Appliances
Most modern medical equipment and appliances have small and programmed computers. The circuitry
and logic in most of the medical equipment is basically a computer. For example, the functioning of
hospital-bed beeping systems, emergency alarm systems, X-ray machines and several such medical
appliances is based on computer logic. Computer software is also used for diagnosis of diseases.
Computer-based systems are used to examine internal and delicate organs of the body. Some of
the complex surgeries can be performed with the aid of computers. Medical imaging is a vast field
that deals with the techniques to create images of the human body for medical purposes. Many of
the modern methods of scanning and imaging are largely based on the computer technology such as
magnetic resonance imaging (MRI).
Electronic Medical Records (EMR)
The use of computers in helps in gathering and storing data about patients. Computers are used in
places such as emergency and intensive care for vital sign monitoring, calculations of cardiac output,
and even pulmonary artery pressure. This allows the focus to be solely on the patient and helps in
the comparison of a patient’s present condition to earlier conditions. Computers are also useful in
documenting nurse’s observations. Computer programs either offer nurses a library of common phrases
that they can pick to describe the patient’s condition, or they are offered a series of questions that

Muhammad Aminu Ahmad Page 65


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

they answer to describe the patient’s condition. There is also documentation on the computer that
lists all the personnel that worked on patient’s case.
Electronic medical records (EMR) have increased the efficiency of hospitals by making patient
information readily available and saving office space for the storage of records. It has also eliminated
illegible handwriting, decreases on data-entry errors and automatically connects related records.
Through means of security, only authorized individuals have access to medical records. The computer
even keeps track of the history of those who have visited certain records. Most significantly, EMR has
dramatically reduced the need for paper and storage services.
Telemedicine
Telemedicine is defined as the use of telecommunications technology to deliver medical diagnosis and
patient care to sites that are distant from the provider. This includes health care delivery, diagnosis,
consultation, treatment, education and transfer of medical data. Telemedicine uses computers and
a large array of technologies to distribute health care and educational services, including plain old
telephone service (POTS), cellular systems, integrated services digital network (ISDN), T-1 and T-3
lines, satellite, and terrestrial microwaves. Besides health care delivery, telemedicine is widely used for
distance learning and continuing medical education for community health providers who do not have
access to information.
Well-known examples of telemedicine include: teleradiology (radiographic images are transmitted
to radiologist for interpretation), telepathology (a pathologist can look down and in some cases,
control a microscope located several hundreds miles away), telepsychiatry (a real-time telemedicine
application that is offered routinely as a service in USA and Australia) and surgical telemedicine
(used for post-residency surgical education). From educational perspective, video-conferencing may
supplement supervised hands-on training in the instruction of a new procedure. From a clinical
perspective, remote patient evaluation, consultation, triage decision and non-operative treatment are
considered acceptable applications of remote surgical practice. Teledermatology, home telenursing and
minor injuries telemedicine are also in practice.
Pharmaceutical Analysis
Computers in pharmaceutical analysis are mainly utilized for data storage, processing of data and
searching of various files. Also various instruments like UV visible spectrophotometer Infra red
instrument, HPLC, microscopes, mass spectrometer come along with particular software. The software
do all necessary process required for analysis purpose. Also these programs contain inbuilt libraries that
are useful for searching of data related to different chemical entities. For example if a mass spectrum
of any unknown chemical is obtained then instructions can be given to the program to find out similar
mass spectrum among the library that is present in it, which will help to find out unknown chemical
entity.
Computer Added Drug Design
Drug design, also sometimes referred to as rational drug design, is the inventive process of finding new
medications based on the knowledge of the biological target. This type of drug design can be assisted

Muhammad Aminu Ahmad Page 66


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

by computer software. Software will generate a number of lead molecules depending upon the feed data
and among these; compound of interest can be developed and tested. If such process is carried out
manually then it will be time consuming and tedious. But the use of computers significantly reduces
the time. Molecular modelling and molecular graphics have shown dramatic growth and are becoming
integral part of drug discovery process.
Molecular modelling is the generation, manipulation and representation of three dimensional form
of molecule. Molecular graphics refers to the use of computer graphics to represent the molecular
structure. In the past synthetic chemists have used molecular models, but computer modelling has
enhanced the detailed display of molecular structures. Various types of software are available, like
AutoDock, CombiBUILD, DockVision, HINT, LIGPLOT and SITUS.
Clinical Trials
Clinical trials are the important part of current drug development which provides information about
risk and benefits of any medication. Data collection and management are very crucial in clinical trials.
The astonishing advancement in computer hardware and software technology had tremendous impact
on clinical trials, data collection and management. E-clinical software consist of integrated suites of
applications that support clinical research process, including various ways of data collection, data entry,
remote data capture, batch data load. These suites enable users to quickly and easily design studies
and capture clinical data. Some examples of e-clinical software are (1) Oracle clinical V4i from Oracle
Corporation; (2) Data LabsXC from Data labs, Inc.; (3) Trial master from Omnicomm systems; (4)
Cliniplus Data Management from DZC software solution, Inc. and (5) Openclinica by Akaza research.
Pharmacokinetics
Pharmacokinetics is the science that deals with the rate of absorption, metabolism, distribution and
elimination of drug and its metabolites in the body. Pharmacokinetic analysis is basically carried out
to get information on renal clearance, volume of distribution, metabolic deposition, absorption and
multiple dosing of drug. This type of analysis can be conducted using software. Classically, long manual
calculations had to be performed and semi-logarithmic paper was used for drawing plots. Now these
computations can be left to the computer. There are different approaches to pharmacokinetics using
differential equations with the help of software. NONLIN is a software that allows users to perform
statistical regression analyses to estimate the values of parameters for linear, multivariate, polynomial,
and general nonlinear functions. The regression analysis determines the values of the parameters that
cause the function to best fit the observed data that you provide. KINPAK is a software used to obtain
Area Under Curve (AUC), peak plasma concentration (Cmax) and peak plasma time (tmax). ESTRIP
and STRIPACT are programs that are also used for mathematical analysis. These software help in
therapeutic drug monitoring of patient. Other applications such XLSTAT, OpenStat, Prism, SAS,
Minitab, SYSTAT and MYSTAT are used for calculation of regression analysis.

5.11 Defence
The high computation capability of computers was initially utilized in major weapon systems and
Electronic Warfare (EW). The advent of microprocessors enables computers to be used in every area of

Muhammad Aminu Ahmad Page 67


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

military equipment and operations. The need for accurate and timely information is vital for Defence.
Computers with their high speed and unlimited storage are revolutionizing the concept of warfare.
Weapon Systems
Computers are used in the following weapon systems:

• Armoured Vehicles: Computers are used in displaying real-time battle situation, setting guns
for azimuth and elevation, providing accurate information for engaging enemy tanks and tactical
targets, and information on terrain, obstacles, routes and state of armoured fighting vehicles.

• Night Vision: Microprocessor-controlled night vision systems are increasingly being used in
basic infantry and anti-tank weapons for higher accuracy during nights. Mobile computer systems
are being employed for a wide range of communications network and general purpose computing
need at forward field locations.

• Fighter Aircraft: Complex computer systems are essentially required for high performance
fighter aircraft. Extensive use of microprocessor-based cockpit instrumentation made it possible
to give accurate and timely information to the fighter pilot. Separate on-board computer systems
assist in navigation in adverse environmental and tactical situations.

• Missiles: Computer are used in all types of strategic and tactical missile systems to improve their
accuracy. In surface-to-surface ballistic and cruise missiles, a very powerful on-board processor
capable of image processing is used to navigate the missiles to the target. In air-to-surface
missiles, microprocessors have extensively been used to process on-board parameters to correct
their course. In surface-to-air missiles, both in the ground and the on-board systems, powerful
computers are utilized to ensure high probability of hit.

Surveillance and Communication Systems


Computers together with satellites, aircraft sensors and telecommunication networks are used in
surveillance and communication systems to provide accurate information to commanders at various
levels to exercise effective command and control using reliable communication. Surveillance is gathering
information with respect to the position of an enemy, resources and capabilities. This is obtained
by satellites, radars, sonar, EW equipment installed on land, in ships and in aircraft or in space.
Communications is transmitting the information gathered in surveillance to locations where such
information could be processed and analysed. The decisions based on such analysis are communicated
to the theatres of action. A variety of communication links such as satellite links are employed for this
purpose. In each of these systems, computer technology plays a major role by reducing the time spent
in collecting accurate information and transmitting the information for analysis.
Simulation and Wargaming
Fast and powerful computer systems and efficient simulation software make it possible to configure
and develop real-time man-in-loop simulation system. It provides cost-effective and time-saving
support towards design, development and training programs in respect of complex military systems.

Muhammad Aminu Ahmad Page 68


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

Simulation is an extremely useful technique, which enables better understanding of dynamic behaviour
of complicated physical systems through mathematical modelling. The real-time ground-based simulator
systems have proved efficient in providing training to human operators, without putting them at risk
on the real-life system being simulated. This also increases the operational life of the sophisticated
military equipments and expensive modern weapon systems, which otherwise would have to be utilized
for training.
Another major area where computer systems have been effectively utilized is wargaming, A simulation
of battlefield situation is provided to different levels of commanders to test their professional skills
and decision-making capabilities. A computer system provides flexibility of use of the visual displays
for different operations of war. Highly complex situations can be simulated with the help of powerful
computers. A number of dynamic simulation probabilistic models for different types of battles have
been developed and are being utilized to determine the effectiveness of battle tactics.

Muhammad Aminu Ahmad Page 69


Chapter
6
Computer Ethics and Responsibility

6.1 Introduction
Every profession operates with a set of ethics that help to define the responsibilities of people who
practice the profession. Computers present a range of capabilities that can affect people and the
environment by challenging society with many new ethical issues. Some of the existing ethical practices
apply to the use of computers, whereas other situations require new ethical rules. In some cases, there
may not be established guidelines, but it is up to the user to decide what is ethical.
A computer professional has knowledge to access computers, program them and manipulate data.
This gives a computer professional the ability to create new products, solve important problems and
help people to manage their interactions with the society. Knowledge of computers can be a powerful
means to effecting positive change. However, computer knowledge can be used in unethical ways. A
computer can be programmed for hacking and unauthorised activities, to sabotage a competitor’s
production line or to steal sensitive information. In addition, it is illegal to copy or distribute computer
software without the permission of the owner because it is an intellectual property. Intellectual
property is creations (books, software, videos, etc.) that are protected by law. Copyright is protecting
intellectual property from copying by others for a period of years. This chapter discuss some ethical
and professional responsibilities of using computers and the Internet.

6.2 Software Piracy


Computer software is easy to copy. However, software buyers only own the right to use the software
according to the license agreement. Therefore, it is illegal to copy, resell, lend, rent, lease and distribute
software without the permission of its creator. These acts are called software piracy. Copyright laws
exist to protect the creators of software (and books and art) so that they can make a profit from the
effort and money spent developing the software.
A software package can cost millions of dollars to develop and distribute to retailers. If people make
unauthorized copies of the software, then the owner of the software loses those sales and either has

70
Kaduna State University CSC101 Lecture Note: 2017-2018 Session

to raise its prices to compensate or spend less money to develop improved versions of the software.
Software pirates sometimes have the rational of saying that they just make one copy for their own use.
However, if thousands of people do the same, then it adds up to the lost of revenue for the software
company, which leads to higher prices for everyone.
When a user purchases a copy of a software program, the user is actually buying a software license,
or in the case of an organization that needs many copies, a site license. A software license can only be
copied for backup purposes while site licenses let the organization make a specific number of copies
to be used within that organization only. There are four types of software licenses: public domain,
freeware, shareware and all rights reserved.

• Public Domain License: This has no owner and is not protected by copyright law. It is either
created with public funds, or the ownership was forfeited by the creator. This can be copied,
sold and/or modified.

• General Public License: GPL software has the same restrictions as public domain software,
but cannot be sold for profit.

• Freeware License: This is a copyrighted software that is licensed to be copied and distributed
without charge. However, it is still under the control of the owner.

• Shareware License: This allows people to use the software for a trial period but it is illegal
to copy or modify them without permission since they are copyrighted. The user must pay a
registration fee to the owner for permanent use. Some shareware trials expire on a certain date.
Purchasing the software may also provide a user with a version with more powerful features and
published documentation.

• All Rights Reserved License: This may be used by the purchaser according the exact details
spelled out in the license agreement. People cannot legally posses and use it without the
permission of the owner.

Thus, computer users have an ethical obligation not to engage in software piracy and to try to stop it
from occurring. This rule is not restricted to duplicating copyrighted software, it includes plagiarism of
all or part of code. If someone gives you permission to copy some code, then just like any responsible
writer, you should acknowledge that person with a citation in the code.

6.3 Privacy of Data


The computer enables the compilation of databases containing useful information about people,
companies, geographic regions and so on. These databases allow employers to issue payroll checks,
banks to cash a customer’s check at any branch, the government to collect taxes, and mass merchandisers
to send out junk mail. Even though people may not care for every use of databases, they generally
have positive benefits. However, they also can be used in negative ways. For example, an industrial
spy might steal customer data from a company database and sell it to a competitor, which is obviously
an illegal act.

Muhammad Aminu Ahmad Page 71


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

Any information about a person that is not clearly public should be considered confidential. An
example of public information is a phone number listed in a telephone directory. Private information
includes data that are provided with an understanding that the data will be used only for a specific
purpose such as the data on a credit card application, staff and student records, company payroll,
patient record and so on. Therefore, unauthorised access, viewing and distribution of these information
are unethical and invasion of the owners right to privacy.
Thus, a computer user has a responsibility to avoid taking advantage of special access to confidential
data. The user also has a responsibility to guard that data from unauthorized access. Guarding data
involves shredding old printouts that contain confidential information, keeping backup copies in a
locked cabinet, not using passwords that are easy to guess (such as a name or word), and more complex
measures such as encryption (keeping it stored in a secret coded form).

6.4 Use of Computers and the Internet


A computer can be used to commit an illegal act such as snooping around someone’s personal computer
physically or through remote access, intentionally modifying or destroying files to which one has not been
granted access, releasing computer viruses, stealing passwords or files, exposing personal information
and stealing electronic money. This also involves the use of computer and Internet connection that
belong to an organisation for personal business, viewing, downloading or storing contents that are
illegal or against the policies of the organisation such as pornography, movies, etc.
Thus, computer users have an ethical responsibility never to use or access computer resources without
permission, either physically or through network access, or access an Internet content that is illegal or
against the policy of an organisation.

6.5 Green Computing


Green computing is a movement towards a more environmentally sustainable computing through the
study and practice of efficient and eco-friendly computing concepts. Green computing deals with the
practice of designing, manufacturing, using and disposing of computers, servers, monitors, printers,
storage devices, and networking and communications systems efficiently and effectively with minimal
or no impact on the environment. It is also necessary to reduce the energy consumed by computing
devices. The targeted areas of green computing are portable devices (laptop, tablets, etc.), desktops,
servers, data centres and mobile infrastructures.
Thus, it is the responsibility of a computer user to participate in disposing computing devices
appropriately and reducing the energy consumed by the devices for a clean and sustainable environment
through the following:

• Turn off the computer when not in use, even if it is just for an hour.

• Turn off the monitor when not in use rather than opting a screen saver.

• Use power saver mode

• Switch off Wi-Fi when not in use

Muhammad Aminu Ahmad Page 72


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

• Do not print unless necessary

• Upgrading where possible is preferred rather than replacement

• Dispose computing devices appropriately.

• Use hardware/software with the Energy Star label. Energy Star is a “seal of approval” by the
Energy Star organization of the government (the EPA) as shown in Figure 6.1.

Figure 6.1: Energy Star label

6.6 Ethical Responsibilities


Ethics deals with placing a value on acts according to whether they are good or bad. Every society has
its rules about whether certain acts are ethical or not. These rules have been established as a result
of consensus in society and are often written into laws. Computer ethics is a term used to describe
the ethical and moral principles in computer-based society. Today, laws have been formulated, either
national or international, for illegal use of computer resources, and every computer user is responsible
for knowing the laws. Generally, it is unethical for a computer user to do the following:
1. Use a computer to harm other people: If it is unethical or bad to steal and destroy other
people’s books and notebooks, it is equally bad to access and destroy their computer files.

2. Interfere with other people’s computer work: Computer viruses and or malicious software
are programs that disrupt other people’s computer work by destroying their files, taking huge
amounts of computer time or memory, or by simply displaying annoying messages. Generating
and consciously spreading computer viruses is unethical.

3. Snoop around in other people’s files: Reading other people’s e-mail messages, screens, and
personal documents in their computers is as bad as opening and reading their letters: This is
invading their privacy. Obtaining other people’s non-public files should be judged the same way
as breaking into their rooms and stealing their documents. Text documents on the Internet may
be protected by encryption.

4. Use a computer to steal: Using a computer to break into the accounts of a company, an
individual or a bank and transferring money should be judged the same way as robbery. It is
illegal and there are strict laws against it.

5. Use computer to bear false witness: The Internet can be used to spread false information
as fast as it can spread the truth. Putting out false information to the world is bad. For instance,
spreading false rumours about a person or false propaganda about events is wrong.

Muhammad Aminu Ahmad Page 73


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

6. Use or copy software without payment or permission: Software is an intellectual product.


In that way, it is like a book; obtaining illegal copies of copyrighted software is as bad as
photocopying a copyrighted book. There are laws against both. Information about the copyright
owner can be embedded by a process called watermarking into pictures in the digital format.

7. Use other people’s computer resources without authorization: Multi-user systems


employ user identifications and passwords to enforce their memory and time allocations, and
to safeguard information. A computer user should not try to bypass this authorization system.
Hacking a system to break and bypass the authorization is unethical.

8. Appropriate other people’s intellectual output: Copying a program developed by someone


or an organisation without proper authorization is software piracy and is unethical. Intellectual
property is a form of ownership and may be protected by copyright laws.

9. Develop a program to harm people or society: Software developers have to think about
computer issues in a more general social framework; can the program you write be used in a way
that is harmful to society? If yes, then a person should desist from writing the program.

10. Use a computer in ways that show no consideration and respect: Just like public buses
or banks, people using computer communications systems should be nice to other people. The
fact that you cannot see the people you are interacting with does not mean that you can be rude
to them.

Muhammad Aminu Ahmad Page 74


Chapter
7
Programs and Programming Languages

7.1 Introduction
Software is a general term to describe all forms of programs associated with computer. Software is
usually written to fulfill some needs required by the general public, private industry, government,
medical diagnoses, insurance claims, bank management and legal management. Ideally, software is
meant to make it easier for the user (i.e., the person using the software) to accomplish some task, solve
some problem or entertain him/herself. Regardless of the user’s motivation for using the software,
many problems will arise when trying to develop the software in a way that is efficient and robust, easy
to use, visually appealing and produces correct results. In computer science, the solution is expressed
in terms of a program.

7.2 How Programs Work


A program is a collection of electronic instructions that programmers write using programming languages
for the computer’s central processing unit (CPU) to interpret in order to solve some problem or perform
a specified task. The CPU of a computer can only understand instructions that are written in machine
language. Because people find it very difficult to write entire programs in machine language, other
programming languages were invented. The CPU is an electronic device that is designed to do specific
things. For example, the CPU is designed to perform operations such as the following:

• Reading data from main memory.

• Adding two numbers.

• Subtracting one number from another number.

• Multiplying two numbers.

• Dividing one number by another number.

75
Kaduna State University CSC101 Lecture Note: 2017-2018 Session

• Moving data from one memory location to another.

• Determining whether one value is equal to another value.

These show that the CPU performs simple operations on pieces of data. The CPU does nothing on its
own. It has to be told what to do and that is the purpose of a program. A program is nothing more
than a list of instructions that cause the CPU to perform operations. Each instruction in a program is
a command that tells the CPU to perform a specific operation. Here’s an example of an instruction
that might appear in a program:

10110000

For human readability, this is only a series of 0s and 1s. To a CPU, this is an instruction to perform
an operation; it tells an Intel microprocessor to move a value into the CPU. It is written in 0s and
1s because CPUs only understand instructions that are written in machine language, and machine
language instructions always have an underlying binary structure. A machine language instruction
exists for each operation that a CPU is capable of performing. For example, there is an instruction for
adding numbers, subtracting one number from another, and so forth. The entire set of instructions
that a CPU can execute is known as the CPU’s instruction set.
Programs are usually stored on a secondary storage device such as a disk drive. When a program is
installed on a computer, the program is typically copied to the computer’s disk drive from a CD-ROM,
or perhaps downloaded from a website. Although a program can be stored on a secondary storage
device such as a disk drive, it has to be copied into the main memory, each time the CPU executes the
program. This is illustarted in Figure 7.1. The CPU executes instructions in a program through a
process that is known as the fetch-decode-execute cycle, which consists of three steps:

1. Fetch or read the next instruction in a program from memory into the CPU.

2. Decode the fteched instruction to determine which operation to perform.

3. Execute or perform the operation specified in the instruction.

These steps are illustrated in Figure 7.2.

Figure 7.1: Coping program from storage to memory for execution

Muhammad Aminu Ahmad Page 76


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

Figure 7.2: The fetch-decode-execute cycle

7.3 Programming Languages


Computers do not understand arbitrary instructions written in human language. Instead, computers
have their own languages that they understand. Each of these languages is known as a programming
language.

A programming language is an artificial language designed to automate the task of organizing


and manipulating information, and to express problem solutions precisely.

7.3.1 Machine Language


The internal programming language for a particular chip is called machine language. Writing programs
in machine language is difficult and therefore programmers need an intermediary between themselves
and the machine language. Programmers had to develop computer programs that could translate
instructions, which were easier for programmers to read, write and understand. The instructions
presented to the computer must ultimately be expressed in machine language/ instructions since only
the computer can directly execute machine language. Ultimately, every program has to exist in machine
language for the computer to use it. But for people to be able to write programs effectively, they need
a language that elevates the process above using digits that makes up the machine instruction.
7.3.2 Low-level Language/Assembly Language
The term low-level language is a general term that applies to languages such as assembly language,
which is close to machine language. Assembly language is a low-level language that uses program codes
in place of the ‘0s’ and ‘Is’ of machine language. On the other hand, rather than a cumbersome series
of 1s and 0s, assembly language uses recognized symbols called mnemonics to represent instructions.
An assembler is a program that takes instructions that are meaningful to people and assembles them
into machine languages. The language that an assembler takes as its input is called assembly language.
Assembly language commands correspond with the instruction set of a CPU; each type of CPU that
has a unique instruction set has its own assembly language.

Muhammad Aminu Ahmad Page 77


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

When programmers write programs in assembly language, they use a text editor; a simple word
processor that stores only ASCII to create a source file. The assembler translates the source code
line for line into machine code and creates the executable program file. Programmers seldom write
programs of any significant size in assembly language. Instead they use it to fine-tune important parts
of programs written in a higher language. Assembly language remains important because it gives the
programmer total control of the computer’s CPU, and as a result produces compact, fast and efficient
code.
7.3.3 High level Language
A high level programming language is a set of words, rules and tools that are used to explain (or define)
what to accomplish. High-level languages use more meaningful words and phrases and also provide
facilities for altering program flow. The most actively used programming languages are Java, C, C++,
PHP, Python, C#, VisualBasic, Objective-C, Perl and Ruby. There are four main types of high level
programming language; structured, object-oriented, functional and logic programming languages.
Structured Programming
Structure has been the watchword in computer programming and has been consistent with the view
of computer users. This means that computer program language is effectively planned, organized
and structured. Structured programming languages are functional in nature i.e. they are based on
functions, subroutines that do something such as to display a message on the screen, get some keyboard
input from a user or perform some mathematical process.
A typical program can easily have hundreds of individual functions. In structured programming,
data and functions are district. Functions perform their work and may or may not alter some of the
data in the data pool while accomplishing their task. For example, when a program runs, the CPU
begins executing the statements of the program at its main entry point. Generally, the entry point
is considered to be the first line (or statement) in the source program file code, although in some
languages the main entry point may be elsewhere, and it’s identified by a keyword such as “main”.
After execution of the first statement, control passes on to the next statement and so on, until the
statement has been executed. Then the program ends.
Object Oriented Programming (OOP)
The 1990s saw the beginning in experiencing a “paradigm shift” in software development in terms of
Object Oriented Programming, where concepts of program, data and file structures are integrated in
the concepts of objects and their persistence. Object oriented programming is a program assembly
using pieces, or objects, that encapsulates information with instructions and combine complex steps
into a single procedure. An object on the other hand is a self –contained unit defined within an object
–oriented programming statement and contains both data and functions.
Programs that use object- oriented programming technique still have functions and subroutines
and have structure in the sense that program statements must have precise and accurate grammar,
or syntax. Object orientation is different in that it allows the programmer to think moderately – to
break up a programming project into components. Object oriented programming does not necessarily

Muhammad Aminu Ahmad Page 78


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

offer new capabilities but provides an elegant new approach to programming. However, the programs
are rugged, that is, much less susceptible to problems that plague programs written in a structured
manner. For example, with a traditional program, it is common to fix a problem and to create another
in the process. When you program with objects it is not easy to break a program.
The concepts of object –oriented programming can seem abstract at first, but the resulting benefits
of using objects are many. Programs become simpler, programming becomes faster and the burden of
program maintenance is lessened. The first language to support specifically OOP methods was called
Smalltalk that was developed in the 1970s. In the mid-1980s, versions of existing languages began to
appear with object-oriented features. New versions of C, Pascal and BASIC support object-oriented
extensions and there is also hyper card.
Functional Programming
Functional programming is a programming paradigm for developing software using functions. Functional
programming languages are specially designed to handle symbolic computation and list processing
applications. In functional programming, programs are executed by evaluating expressions and typically
avoids using mutable state. Functional programming requires that functions are treated like any other
values and can be passed as arguments to other functions or be returned as a result of a function, that
is, it is possible to define and manipulate functions from within other functions. Special attention
needs to be given to functions that reference local variables from their scope. Some characteristics of
functional programming are:

• It is designed on the concept of mathematical functions that use conditional expressions and
recursion to perform computation.

• It supports higher-order functions and lazy evaluation features.

• It does not support flow controls like loop statements and conditional statements like If-Else and
Switch Statements. They directly use the functions and functional calls.

• Like OOP, it supports popular concepts such as Abstraction, Encapsulation, Inheritance, and
Polymorphism.

Some of the popular functional programming languages include: Lisp, Python, Erlang, Haskell, Clojure,
etc.
Logic Programming
Logic programming is a computer programming paradigm in which program statements express facts
and rules about problems within a system of formal logic. Rules are written as logical clauses with a
head and a body. For instance, "A is true if B, C, and D are true". Facts are expressed similar to rules,
but without a body. For instance, "H is true". A logic program consists of a set of axioms and a goal
statement. The rules of inference are applied to determine whether the axioms are sufficient to ensure
the truth of the goal statement. The execution of a logic program corresponds to the construction of
a proof of the goal statement from the axioms. Some logic programming languages such as Datalog

Muhammad Aminu Ahmad Page 79


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

and Answer Set Programming (ASP) are purely declarative, that is, they allow for statements about
what the program should accomplish, with no explicit step-by-step instructions about how to do so.
Others, such as Prolog, are a combination of declarative and imperative, that is, they may also include
procedural statements such as "To solve A, solve B, C, and D".
7.3.4 Translation of High-Level Languages
Most computer programs are written in high-level languages. Depending on the language a program
has been written in, the programmer will use either a compiler or an interpreter to make the translation.
The statements that a programmer writes in a high-level language are called source code. Typically,
the programmer types a program’s code into a text editor and then saves the code in a file on the
computer’s disk. Next, the programmer uses a compiler to translate the source code into object code,
which is a machine language version of the program, or an interpreter to translate and execute the
code. If the code contains a syntax error, it cannot be translated. A syntax error is a mistake such as
a misspelled key word, a missing punctuation character or incorrect use of an operator. When this
happens the compiler or interpreter displays an error message indicating that the program contains
a syntax error. The programmer corrects the error and then attempts once again to translate the
program.
Compiler
A compiler is a program that translates a high-level language program (source code) into a separate
machine language program (object code). The machine language program can then be executed any
time it is needed. A compiler translates a whole program completely, and then executes the machine
language version. Using the compiler method is more useful if the same program is to be used again
and again, since the translation gets done only once. As shown in Figure 7.3, the compilation and
execution processes are different.

Figure 7.3: Compiling and executing a high-level program

When using a compiler, two versions of the program are created. The first version, called the source
file program code, is the one written in the high–level language. The compiler takes in this source
program and produces a translated version called the object program code. The object program then

Muhammad Aminu Ahmad Page 80


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

has to be loaded into memory and executed. Some compilers only translate the source program into a
low-level language such as assembly language instead of translating the source program into machine
code. Some further translation is then necessary in order for the program to be executed.
Interpreter
An interpreter is a program that both translates and executes instructions in a high-level language
program. An interpreter reads each individual instruction in the program, converts it to machine
language instructions and then immediately executes them. This process repeats for every instruction
in the program. This process is illustrated in Figure 7.4.

Figure 7.4: Executing a program using an interpreter

Because interpreters combine translation and execution, they typically do not create separate machine
language programs.

Muhammad Aminu Ahmad Page 81


Chapter
8
Problem Solving

8.1 Introduction
The ability to solve problems is a basic life skill and essential to understanding technical subjects.
Basically, problem-solving is the process of reasoning to solutions using more than simple application
of previously learned procedures. For a problem to be solved effectively, it has to have an agreed upon
procedure for solving it. Not all problems are equally important and their relative significance should
be kept in perspective. In a learning environment, most of the needed information is provided: a clear
statement of the problem, the necessary input, and the required output. In real life, the process is not
always so simple. You often have to define the problem yourself and then decide what information
you have to work with and what the results should be. The problems that we want to solve can come
from any real-world problem or perhaps even from the abstract world. We need to have a standard
systematic approach to solving problems. After you understand and analyse a problem, you must come
up with a solution. Thus

Problem Solving is the sequential process of analysing information related to a given


situation and generating appropriate response options.

8.2 Problem Solving Method


Problem solving methods involves the following steps;
8.2.1 Understand and Define the Problem
A good problem definition states the current situation and the desired situation. When defining a
problem, the statement should not imply any solutions or causes. The current situation is defined by
facts; use clear and concise language supported by gathered facts when defining the problem. The
desired situation is defined as an objective, stated in clear, concise, concrete language and be both
realistic and worthwhile. A primary source of ineffectiveness is rushing to solutions before properly

82
Kaduna State University CSC101 Lecture Note: 2017-2018 Session

defining the problem. To define or understand any problem, the following questions have to be
addressed.

• What is the unknown?

• What are the data?

• What is the condition?

• Is it possible to satisfy the condition?

• Is the condition sufficient to determine the unknown? Or is it insufficient? Or redundant? Or


contradictory?

For example,

“calculate the floor area of the board room that is on the ground floor of faculty of science
building in Kaduna State University. The length of the room is 11 meters and the width
is 7 meters. It is the largest room in the building, with 200 seats and provisions for 10
disabled persons”

The problem can be specified by identifying the necessary information and deleting what is unnecessary
to the problem. Therefore the problem can be defined as

“calculate the floor area of the board room that is on the ground floor of faculty of science
building in Kaduna State University. The length of the room is 11 meters and the width
is 7 meters. It is the largest room in the building with 200 seats and provisions for 10
disabled persons””

Thus, you must understand what is involved in the problem before you can continue toward the solution.
This also includes understanding the knowledge base of the domain for which you are solving the
problem. Knowing or understanding the knowledge base is very important since you cannot use any
instructions outside the base. For example, to solve a problem involving calculus or accounting, you
must know or understand accounting, which can be achieved by communicating with the experts and
be able to understand what is involved in solving the problem. After defining and understanding a
problem, analyze it to see the real bottom-line root cause by gathering information. If there is no
enough information, figure out how to search and collect it.
8.2.2 Devise a Plan to Solve the Problem
To solve problems, you must identify and define a plan for the solution. This is a creative as well as
practical step where every possible solution or variation is identified. Brainstorming is a technique
that allows a large number of ideas to be generated. This can be achieved by finding the connection
between the data and the unknown. Devising a plan involves the following.

• Could you restate the problem? Could you restate it still differently? Go back to definitions.

Muhammad Aminu Ahmad Page 83


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

• If you cannot solve the proposed problem, try to solve some related problem. Could you imagine
a more accessible related problem? A more general problem? A more special problem? An
analogous problem? Could you solve a part of the problem? Could you think of other data
appropriate to determine the unknown? Could you change the unknown or data, or both if
necessary, so that the new unknown and the new data are nearer to each other?

• Did you use all the data? Did you use the whole condition? Have you taken into account all
essential notions involved in the problem?

The problem solving techniques that can be used when considering all possible solutions are familiarity,
analogy and divide and conquer.
Familiarity
People are good at recognizing similar situations. Certain problems occur again and again in different
guises. To solve problems, you need to immediately recognise a similar task that has been solved before.
Students do not have to learn how to attend a lecture for every course they take, they know that
attending a lecture is always the same; what differs is the venue of the lecture. For example, finding
the daily maximum and minimum temperatures is similar to finding the highest and lowest grades on
a test. All you need is to know the largest and smallest values in a set of numbers. Therefore, never
reinvent the wheel. If a solution exists, use it. If a similar problem was solved before, just repeat your
solution. Thus, solving a problem using familiarity involves the following:

• Have you seen it before? Or have you seen the same problem in a slightly different form?

• Do you know a related problem? Do you know a theorem that could be useful? Try to think of a
familiar problem having the same or a similar unknown.

• Here is a problem related to yours and solved before. Could you use it? Could you use its result?
Could you use its method? Should you introduce some auxiliary element in order to make its use
possible?

Analogy
A problem often reminds you of another problem you have seen before. You may find solving the
problem at hand easier if you remember how you solved the other problem. In other words, draw
an analogy between the two problems. Analogy is really just a broader application of the strategy
of looking for things that are familiar. When developing a solution, try to get a larger view of the
problem because the best problem solvers are people who have broad experience in solving all kinds of
problems.
Divide and Conquer
This involves breaking up large problems into smaller units that are easier to handle. Cleaning a
whole house may seem overwhelming, but cleaning the rooms in the one at a time seems much more
manageable. The same principle applies to problems. We break up a large problem into smaller pieces
that we can solve individually.

Muhammad Aminu Ahmad Page 84


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

8.2.3 Select the Best Way to Solve the Problem


After devising a set of plans to solve a problem from the list of alternative solutions, you need to
identify and evaluate the advantages and disadvantages of each possible solution before selecting the
best one. In order to do this, you need to select criteria for the evaluation. These criteria will serve
as the guidelines for evaluating each solution. The criteria can be weighted if some solutions are
more important than others. A score is assigned to each criterion based on the extent to which that
solution meets the criterion. For example, use a scale of one to ten with ten the highest score. After
selecting the best possible solution, the problem is solved using the selected solution. These numbered,
step-by-step instructions must fall within the knowledge base set up when devising the plan.
8.2.4 Test and Evaluate the Solution
To test and evaluate a solution means to check its result to see if it is correct, and to see if it satisfies
the needs of the person(s) with the problem. If the result is either incorrect or unsatisfactory, then the
problem solver must review the list of instructions to see that they are correct or start the process all
over again.

8.3 Algorithmic Problem Solving


Algorithmic problem solving is the use of algorithms to develop solution for a given problem. Problems
do not always have straightforward solutions, some can be solved with a series of actions while some
are not. Solutions that can be achieved through a series of actions are called algorithmic solutions,
while solution that can not be reached through a direct set of steps are called heuristic solutions.
8.3.1 Algorithm
The term algorithm originally referred to any computation performed via a set of rules applied to
numbers written in decimal form. The word is derived from the phonetic pronunciation of the last
name of Abu Ja’far Muhammad ibn Musa al-Khowarizmi, an Arabic mathematician that invented a
set of rules for performing the four basic arithmetic operations (addition, subtraction, multiplication
and division) on decimal numbers.

An algorithm is a procedure consisting of a finite set of unambiguous rules (instructions)


which specify a finite sequence of operations that provides solution to a problem, or to a
specific class of problems for any allowable set of input quantities (if there are inputs). In
other words, an algorithm is a procedure that accepts data, manipulate them following the
prescribed steps, so as to eventually fill the required unknown with the desired value(s), or
a precise sequence of instructions for solving a problem.

A recipe in a cookbook is an excellent example of an algorithm. The recipe includes the requirements
for the cooking or ingredients and the method of cooking them until you end up with a nice cooked
dish.
Characteristics of an Algorithm
There are four essential properties of an algorithm.

Muhammad Aminu Ahmad Page 85


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

• Each step of an algorithm must be exact. An algorithm must be precisely and unambiguously
described, so that there remains no uncertainty.

• An algorithm must terminate. The ultimate purpose of an algorithm is to solve a problem. If the
program does not stop when executed, we will not be able to get any result from it. Therefore,
an algorithm must contain a finite number of steps in its execution.

• An algorithm must be effective, that is, an algorithm must provide the correct answer to the
problem.

• An algorithm must be general. This means that it must solve every instance of the problem. For
example, a program that computes the area of a rectangle should work on all possible dimensions
of the rectangle, within the limits of the programming language and the machine.

Algorithm Design and Analysis


Algorithm design and analysis requires the following sequential steps.

• Understand the problem: Do some examples by hand, think about special cases, ask questions if
needed. May be you can use a known algorithm for solving it.

• Ascertaining the capabilities of a computational device: Sequential (serial) algorithms versus


parallel algorithms.

• Choosing between exact and approximate problem solving.

• Deciding on appropriate data structures; structuring or restructuring data to specify the instance
of a problem.

• Algorithm design techniques; select a general approach to solving problem algorithmically.

• Methods of specifying an algorithm; pseudo-code is a mixture of a natural language and a


programming language-like constructs. Flowchart is A diagram that uses graphic symbols to
depict the nature and flow of the steps in a process or algorithm.

• Providing the correctness of the algorithm.

• Analysing an algorithm; time and space efficiencies, and simplicity and generality of the algorithm.

• Coding an algorithm: Implement it as computer program with test and debugging for its
validation.

Presentation of Algorithm
Algorithms are usually presented in the form of some pseudo-code or flowchart.

Muhammad Aminu Ahmad Page 86


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

Pseudo-code
A pseudo-code is one of the tools that can be used to write a preliminary plan that can be developed
into a computer program. A pseudo-code is a generic way of describing an algorithm without the use
of any specific programming language syntax. It is, as the name suggests, pseudo code —it cannot be
executed on a real computer, but it models and resembles real programming code, and is written at
roughly the same level of detail. The syntax used in pseudo-code is borrowed popular programming
languages. Thus

A pseudo-code is a simple and concise sequence and mixture of English-like instructions,


some mathematical notations, and selected keywords from a programming language to solve
a problem.

There is no standard convention for writing pseudo-code; each author may have his own style, as long
as clarity is ensured. Below is an algorithm written in pseudo-code. The problem concerned is to find
the minimum, maximum and average of a list of numbers.
1: BEGIN
2: Sum, count = 0
3: min = ?
4: max = ?
5: for each num entered do
6: increment count
7: sum = sum + num
8: sum = sum + num
9: if num < min then
10: min = num ElseIfnum > max
11: max = num
12: end if
13: average = sum/count
14: end for
15: END

Flowchart
Flowcharting is a tool developed in the computer industry, for showing the steps involved in a process.
A flowchart is a diagram made up of boxes, diamonds and other shapes, connected by arrows - each
shape represents a step in the process and the arrows show the order in which they occur. Thus

Flowcharting is a graphical way of specifying the finite set of instruction for solving a
problem.

Flowcharting combines symbols and flow lines to show figuratively the operation of an algorithm.
There are different symbols used in flowcharting (there are even national and international flowcharting
symbol standards). Figure 8.1 shows the basic symbols commonly used in flowcharting: Terminal,
Process, Input/Output, Decision, Connector and Predefined Process.

Muhammad Aminu Ahmad Page 87


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

Figure 8.1: Basic flowchart symbols

This is not a complete list of all the possible flowcharting symbols. It is the set of symbols that are
often used. The general rules of flowcharting are:

• All boxes of the flowchart are connected with Arrows. (Not lines)

• 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.

• The decision symbol has two exit points; these can be on the sides or the bottom and one side.

• 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.

• 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 than 3 symbols.

• Subroutines and interrupt programs have their own flowcharts.

• All flow charts start with a terminal or Predefined Process (for interrupt programs or subroutines)
symbol.

• All flowcharts end with a terminal or a contentious loop.

Muhammad Aminu Ahmad Page 88


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

8.4 Problem Solving Examples


Solving problems using algorithm require the use of three basic methods of control: sequence, selection,
and repetition. Some problems can be solved by using a combination of the methods.
8.4.1 Sequence
Sequential control means that the steps of an algorithm are carried out in a sequential manner where
each step is executed exactly once. When using sequence control, every step is executed once in
sequential order. No step is left out and no step is repeated. Once all the steps are executed, the
problem should be solved. But, if the problem is not solved, it indicates a logical error in the program.
It may be that a step is written incorrectly or a step is left out.
Example 1
Calculate the weekly earning of an employee if the hours he worked and the hourly rate are entered by
the user after deducting 20 Naira as weekly tax.
Solution
The first step to solving any problem is to decompose the problem description. The nouns in the
problem specification describe the information needed to either identify or keep track of. Once these
nouns are identified, they should be grouped into one of two categories: input (items that are known
or received from the user) and output (items to be identified by manipulating the input). In this case,
the the nouns are categorised as:

Inputs: employee, hours, rate, user, tax

Output: earning

Identify all of the verbs in the sentence. The verbs in the problem describe the actions your algorithm
needs to take. These actions, known as processing are the steps between the input and output.

Process: calculate

Eliminate the inputs that are not necessary in solving the problem and link the inputs, processes and
output.

Inputs Processing Output

Employee
Hours Calculate Earning

Rate
User
Tax

Now we need to determine what calculate refers to in this problem. Calculate could mean applying
some mathematical formula or other transformation to our input data in order to reach the desired
output. In this case, using our elementary mathematics, the earning of an employee can be determined
using the following formula:
Earning = (Hours ∗ Rate) − 20

Muhammad Aminu Ahmad Page 89


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

Therefore, apply the formula to solve the problem.

1: BEGIN
Start
2: Inputs: Hours and Rate
3: Earning = (Hours * Rate) - 20
4: Display Earning
Get user input
5: END (Hours and Rate)

Earning=(Hours x Rate)-20

Display results
(Earning)

Stop

Example 2
A jewellery store has a sale on diamonds. A customer will get 30% discount off the list price but must
pay 13% tax on the discounted price. Write an algorithm to calculate the final price of any given list
price.
Solution

1: BEGIN Start
2: Inputs: Price
3: NewPrice = Price - (0.30 * Price)
Get user input
4: FinalPrice = NewPrice + (0.13 * NewPrice) (Price)

5: Display FinalPrice
6: END Discount=0.30 x Price

NewPrice =Price - Discount

Tax = 0.13 * NewPrice

FinalPrice = NewPrice + Tax

Display result
(FinalPrice)

Stop

8.4.2 Selection
The complexity of a problem may require choose an option rather than applying statements in sequence
only. An algorithm may therefore include the possibility of providing for different options that may
change the course of the flow of the statements in the algorithm. To enable the use of this type
of logic in an algorithm, a selection (decision/branching) control statement may be included in the

Muhammad Aminu Ahmad Page 90


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

algorithm which is based on relational and logical operators. In selection control, only one of a number
of alternative steps is executed.
Example 3
The employees of a company receive an increase of 8%, but the employees in department A (that
performed the best) receive an increase of 10%. Write an algorithm to determine the salary of a given
employee.
Solution

1: BEGIN Start
2: Inputs: Salary and Department
3: if Department = A then
Get user input
4: NewSalary = 0.1 * Salary (Salary and Deparment)

5: else
6: NewSalary = 0.08 * Salary Is Ye s NewSalary = (0.1 x Salary) + Salary
Department = “A”
7: end if
8: Display NewSalary No

9: END
NewSalary = (0.08 x Salary) + Salary

Display result
(NewSalary)

Stop

Example 4
A salesperson earns 7% monthly commission on her 2000 Naira sales income, a 10% commission on
sales income over 2000 Naira but less than or equal to 5000 Naira, and 15% commission on sales income
above 5000 Naira. Write an algorithm that will take the total sales amount for a month and compute
the salesperson’s commission and the net income the company receives after the commission has been
deducted.
Solution
1: BEGIN
2: Inputs: SalesAmount
3: if SalesAmount = 2000 then
4: Commission = 0.07 * SalesAmount
5: NetIncome = SalesAmount - Commission
6: else if SalesAmount > 2000 and SalesAmount <= 5000 then
7: Commission = (0.07 * SalesAmount) + (0.1 * (SalesAmount - 2000))
8: NetIncome = SalesAmount - Commission
9: else if SalesAmount > 5000 then
10: Commission = (0.07 * SalesAmount) + (0.1 * (SalesAmount - 2000) + (0.15 * (SalesAmount - 5000))
11: NetIncome = SalesAmount - Commission
12: else
13: Commission = 0
14: NetIncome = SalesAmount
15: end if
16: Display Commission and NetIncome
17: END

Muhammad Aminu Ahmad Page 91


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

Start

Get user input


(SalesAmount)

Is Yes Comm = 0.07 × salesAmount


SalesAmount = 2000?

No

Is
SalesAmount > 2000
Ye s Comm = (0.07 × 2000) + (0.10 × (salesAmnt – 2000))
and
SalesAmount < = 5000?

No

Is
Ye s Comm = (0.07 × 2000) + (0. 10 × (salesAmnt – 2000)) + (0.15×(salesAmnt-5000))
SalesAmount > 5000?

No

NetIncome = SalesAmount NetIncome = SalesAmount - Comm

Display result
Display result
No commisssion and,
(Comm And NetIncome)
NetIncome is salesAmount

Stop

8.4.3 Repetition
Problem solving very often includes repeating a set of instructions a number of times. Sometimes we
know exactly how many times we need to repeat the instructions and other times we do not know. This
technique is also called iteration or looping. In repetition one or more steps are performed repeatedly.
Example 5
Write an algorithm to read integers between 5 and 20 until their sum is greater than 200. Display the
sum and the number of integers entered.
Solution

1: BEGIN Start Start

2: Sum = 0, count = 0
3: while (Sum <= 200) do Sum = 0 Sum = 0
Count = 0 Count = 0
4: Number = Get user input
5: Sum = Sum + Number Is
Get user input
(Number)
Sum > 200
6: Count = Count + 1 Ye s

7: end while No Sum = Sum + Number

Get user input


8: Display Sum and Count (Number)
Count = Count + 1
9: END
Sum = Sum + Number
Is
No
Sum > 200
Count = Count + 1
Yes

Display results Display results


(Sum and Count) (Sum and Count)

Stop Stop

Muhammad Aminu Ahmad Page 92


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

Example 6
Yusra offered to pick strawberries for her mother who wants to cook jam. She needs at least 5.5
kilograms of strawberries for the jam. Yusra can pick and bring between 400 and 900 grams of
strawberries at a time to empty her basket into her mother’s container on the scale. Write an algorithm
that reads the weight of the strawberries in grams every time Yusra brings strawberries. The algorithm
must calculate and display how many times Yusra has to go to the garden to pick strawberries before
her mother has enough to cook. The algorithm must also display the total weight of the strawberries
picked.

Solution

1: BEGIN Start Start

2: TotalWeight = 0, Trip = 0
3: while (TotalWeight < 5.5kg) do TotalWeight = 0 TotalWeight = 0
Trip = 0 Trip = 0
4: Weight = Get user input
5: TotalWeight = TotalWeight + Weight Get user input
Is (Weight)
6: Trip = Trip + 1 TotalWeight >= 5.5 Kg

7: end while No
Yes
TotalWeight = TotalWeight + Weight

8: Display Trip and TotalWeight Get user input


(Weight)
No
Trip = Trip + 1
9: END
TotalWeight = TotalWeight + We ight
Is
TotalWeight >= 5.5 Kg

Trip = Trip + 1
Yes
Display re sults
(Trip and TotalWeight) Display results
(T rip and TotalWeight)

Stop Stop

Example 7
An electric and gas stoves company pays each of the company’s salesperson a commission of 20%
based on the total number of his or her sales. Write an algorithm that allows the user to enter the
salesperson’s name and the amounts of electric and gas stoves sold. It should then calculate the
commission on the sum of the sales amounts and display the name and commission for each of the
salespeople. A salesman name of “END” is entered to indicate the end of the input data. The total
sales and total commission on sales of all salespersons should also be calculated and displayed.
Solution
1: BEGIN
2: TotalSales = 0, TotalCommission = 0
3: Name = Get user input
4: while (NAME is not "End") do
5: SalesAmount = Get user input
6: Commission = 0.2 * SalesAmount
7: TotalSales = TotalSales + (SalesAmount - Commission)
8: TotalCommission = TotalCommission + Commission
9: Display Name and Commission
10: Name = Get user input
11: end while
12: Display TotalSales and TotalCommission
13: END

Muhammad Aminu Ahmad Page 93


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

Start

TotalSales = 0
TotalComm = 0

Get user input


(Name, SalesAmount)

Is
Name =”END”

No

Comm = 0.2 x SalesAmount

Sales = SalesAmont-Comm

Ye s

TotalSales = TotalSales + Sales

TotalComm = TotalComm + Comm

Display results
(Name and Comm)

Display re sults
(T otal Sa le s and Total Comm)

Stop

8.4.4 Selection and Repetition


Most of the problems analysed in sections 8.4.2 and 8.4.3 were solved using a combination of sequence and selection or sequence
and repetition methods. This section presents problems that require the use of selection and repetition methods for solution.

Example 8
A number of students were admitted in a university during the first week of January and the weight of each student was written
on their registration card. During the last week of November, every student was weighed again and their new weights were also
written on their registration cards. Write an algorithm to read the name, first weight and last weight. Calculate the weight loss or
gained and display name and weight loss or gained. The algorithm should also calculate and display the average weight loss and
average weight gain at the end.
Solution

1: BEGIN
2: AverageweightLoss = 0, AverageweightGain = 0, LossCount = 0, GainCount = 0
3: Name = Get user input
4: while (NAME is not "End") do
5: FirstWeight = Get user input
6: LastWeight = Get user input
7: if (FirstWeight > LastWeight) then
8: WeightLoss = FirstWeight - LastWeight
9: TotalWeightLoss = TotalWeightLoss + WeightLoss
10: LossCount = LossCount + 1
11: Display Name and WeightLoss
12: else if (FirstWeight < LastWeight) then
13: WeightGain = LastWeight - FirstWeight
14: TotalWeightGain = TotalWeightGain + WeightGain
15: GainCount = GainCount + 1
16: Display Name and WeightGain
17: else
18: Display "No weight loss of gain"
19: end if
20: Name = Get user input
21: end while
22: AverageWeightLoss = TotalWeightLoss / LossCount
23: AverageWeightGain = TotalWeightGain / LossGain
24: Display AverageWeightLoss and AverageWeightGain
25: END

Muhammad Aminu Ahmad Page 94


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

Start

AverageWeightloss = 0
AverageWeightGain =0
LossCount = 0
GainCount = 0

Ge t use r input
(Name )

Is
Name = “End”

No

Ge t use r input
(FirstWeight, LastWeight)

We ightLoss = FirstWeight – LastWe ight


Is Display results
Yes TotalWeightLoss = TotalWeightLoss + WeightLoss
FirstWeight > LastWeight (Name WeightLost)
LossCount = LossCount + 1

Ye s
No

Is We ightGain = LastWeight – FirstWeight


Display re sults
Ye s TotalWeightGain = TotalWeightGain + WeightGain
FirstWeight < LastWeight (Name WeightGain)
Ga inCount = gainCount + 1

No

Display results
(No Weight loss or Gain)

Display re sults
AverageWeightLoss = TotalWeightLoss / LossCount (A ve rageWeighLoss,
AverageWe ightLoss = TotalWeightLoss / LossCount
AverageWe ightGain)

Stop

Example 9
Sharon went for shopping and bought a number of different items. She picked a number of items to purchase and went to the
paying machine to check out using her bank card. Write an algorithm to read the amount of money in her bank account and the
price of every item. Calculate the total amount of the items she picked. After the prices of all the items are entered, a price of 0
(zero) is entered to indicate that she has finished picking items to buy. If the total amount she spent is more than 500 Naira, she
will receive a discount of 5%. If the money in her bank account is enough to pay for her shopping, calculate and display how much
money she spent. If her balance is not enough, display a message to indicate how much more money she will need to pay for her
shopping.
Solution

1: BEGIN
2: TotalAmount = 0
3: ItemPrice = Get user input
4: while (ItemPrice > 0) do
5: if (TotalAmount > 500) then
6: AmountToPay = 0.05 x TotalAmount
7: if (Balance >= AmountToPay) then
8: Display "You spend AmountToPay"
9: else
10: AmountNeeded = AmountToPay - Balance
11: Display "You need AmountNeeded"
12: end if
13: else
14: if (Balance >= TotalAmount) then
15: Display "You spend TotalAmount"
16: else
17: AmountNeeded = TotalAmount - Balance
18: Display "You need AmountNeeded"
19: end if
20: end if
21: end while
22: END

Muhammad Aminu Ahmad Page 95


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

Start

TotalAmount

Get user input


(I temPrice)

Is
No Total Amount = Total Amount + ItemPrice
ItemPrice = 0

Ye s

Is Is Display re sults
No Ye s
Total Amount > 500 Balance > TotalAmount (You spe nd TotalAmount)

Ye s No

AmountToPay = 0.05 x T otalAmount AmountNeeded = TotalAmount-Balance

Is
No AmountNeeded = AmountToPay-Balance
Balance >= A mountToPay

Ye s

Display re sults Display re sults


(You spe nd AmountT oPay) (You need AmountNeeded)

Stop

Muhammad Aminu Ahmad Page 96


Chapter
9
Python Essentials

9.1 Introduction
Python is an interpreted language, that is, it uses an interpreter to run programs that are saved in files, or interactively execute
statements that are typed in the console through the keyboard. Python comes with a program named IDLE that simplifies the
process of writing, executing, and testing programs. This chapter is concerned with developing programs to solve problems using
Python programming that will be executed on command line. Python is named after Monty Python and its famous flying circus,
not the snake. It is a trademark of the Python Software Foundation.

9.2 Python Interpreter


Basic operations such as addition (+), subtraction (-), multiplication (*), division (/), remainder (%) and exponentiation (**) can
be done using the Python interpreter. The interpreter acts as a simple calculator; it enables typing an expression at the prompt
and it will write the value. Consider the following example:

The python prompt (the chevron >>>) signals that Python is waiting for input. The first expression 6+8 was typed in the Python
prompt followed by a carriage return or the Enter key on the keyboard. The Python interpreter then displays the result as 14
and then waits for input again. The subsequent expressions were also entered and the Python interpreter displayed the results
accordingly.

9.3 Variables and Expression


A variable is an identifier that can be used to store a certain value or object. A variable is created through assignment:

97
Kaduna State University CSC101 Lecture Note: 2017-2018 Session

The variable “a” is created and the value “9.6” is assigned to the variable. Having declared “a” as a variable, it can be used to
perform operation. For example:

Variables must be created (assigned a value) before they can be used, or an error will occur. A variable is overridden if a new value
is assigned:

The equal sign (=) is used to assign a value to a variable. Afterwards, no result is displayed before the next interactive prompt. A
value can be assigned to several variables simultaneously. For example:

A variable name is not restricted to a single letter, it can be a word or a combination of words without space or with underscore
between two letters. For example:

In computer programs we often encounter statements like

If we read this as an equation in mathematics,


a=a+1

then a is subtracted on both sides, and the result is 0 = 1, which is not true. Equations in computer codes are not equations but
assignments. They always have to be read in the following way two-step way:

1. Evaluate the value on the right hand side of the equal sign; so if a is currently 8, the right hand side 8+1 evaluates to 9.

2. Assign this value (9) to the variable name shown on the left hand side a.

The correct interpretation is shown in the Python prompt:

It is a common operation to increase the value of a variable by some fixed amount. Therefore, we can write a = a + 1 as a+ = 1.
This will increment the value of a by 1. Similarly, a+ = 5, will increment the value by 5. The same condition holds for the other
operators; a− = 1, a/ = 2, a∗ = 5, etc.

9.4 Data Types


Python used different data types such as numbers (integer, long, floating point and complex numbers), boolean (true or false) and
sequences (string, list and tuples).

Muhammad Aminu Ahmad Page 98


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

9.4.1 Numbers
The numerical types used by Python are integers, floating point numbers and complex floating point numbers. Python also has
long integers, which have no upper or lower limit (assuming the machine provides enough memory).
Integers:

Floating point numbers:

Complex numbers:

9.4.2 Boolean
The Boolean type is limited to two values: True and False. For example:

Python uses many logical operators that result in a Boolean type; <, >, = =, >=, <=, !=, is, in, not and, or, etc. For example:

The operators “= =”, “<” and “>” and “!=” checks the equality of the values of objects a and b, while the operator “is” check the
equality of the objects a and b. The “is” operator checks whether a and b are references to the same place in memory, which is not
the same. This can be verified using the id function as shown in the preceding example. Thus, the “is” operator can be used to
know the identity of an object. For example:

Muhammad Aminu Ahmad Page 99


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

Here, a and b are identical because they are references to the same piece of memory, which is confirm by the id function.
The “in” operator is used to check the presence of an object in a sequence and returns a Boolean type. For example:

Python uses the < and > operators for alphabetic ordering. For example:

9.4.3 String
Beside numbers, Python can also manipulate strings, which can be expressed in several ways. A string is a (immutable) sequence
of characters. A string can be defined using single or double quotes. For example:

Strings can be combined using the + operator. The type of a string is “str” and the empty string is given through " ". The number
of characters in a string (that is its length) can be obtained using the len() function. For example:

Strings have a number of useful methods, including for example upper() which returns the string in upper case:

9.4.4 List
Python uses compound data types that enable grouping values. The most versatile is the list, which can be written as a list of
comma-separated values (items) between square brackets. List items must not have the same type. For example:

Muhammad Aminu Ahmad Page 100


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

As with strings, the number of elements in a list can be obtained using the len() function. Similarly, lists can also be combined
with + operator. For example:

Objects can be added into a list using the append() method. For example:

An object can be deleted from a list by calling the remove() method and passing the object to delete. For example:

List methods include the following:

• append(x) – add x to the end of the list

• extend(L) – add all items in sequence L to end of list

• insert(i,x) – insert x at a position i

• remove(x) – remove first item equal to x

• pop([i]) – remove item at position i or end of list

• index(x) – return index of first item equal to x

• count(x) – count occurrences of x

• sort() – sort the list

• reverse() – reverse the list

9.4.5 Tuples
A tuple is a sequence of objects. Tuples are very similar in behaviour to lists with the exception that they cannot be modified, i.e.,
they are immutable. A sequence of objects separated by commas defined a tuple. It can be in parentheses or not. For example:

It is a good practice to include the parenthesis when defining a tuple. An empty tuple is defined using (). For example:

The notation for a tuple containing one value is appended with a comma. For example:

Muhammad Aminu Ahmad Page 101


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

The extra comma is required to distinguish (5,) from (5), because the latter case defined operator precedence, i.e., (5) simplifies to
5, which is just a number. Tuples are used when we do not want the content to change. The immutability is the main difference
between a tuple and a list.

9.4.6 Indexing Sequences


Individual objects in strings, lists and tuples can be accessed by using the index of the object and square brackets. For example:

Python provides a way of retrieving the last element in a sequence using the index “-1", where the minus indicates that it is one
element from the back of the sequence. Similarly, the index “-2" will return the 2nd last element. For example:

You can think of the index a[-1] to be a shorthand notation for a[len(a) - 1].

9.4.7 Slicing Sequences


Slicing of sequences can be used to retrieve more than one element. For example:

Muhammad Aminu Ahmad Page 102


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

By writing a[0:2] we request the first 2 elements starting from element 0. In slicing, the first number in the square bracket indicates
the start of the operation and the last number indicates one past end as depicted below:

To make a copy of an entire sequence, you can use [:].

9.4.8 Concatenating and Repeating Sequences


Python uses the + operator to produce a new sequence whose value is the concatenation of its arguments. Python also used the *
operator to produce a new sequence that “repeats” the original content of it argument. For example:

9.4.9 Dictionaries
Dictionaries are also called “associative arrays" and “hash tables". Dictionaries are unordered sets of key-value pairs. Dictionaries
store a mapping between a set of keys and a set of values.

• Keys can be any immutable type.

• Values can be any type.

• A single dictionary can store values of different types.

An empty dictionary can be created using curly braces:

The following examples creates a dictionary with two values Alan and 1234 and their keys user and pswd respectively.An entry in
a dictionary can be deleted using the del function.

The key-value pairs in a dictionary can be defined, modified, viewed and looked-up. The function dict() can be used to creates a
dictionary.

Muhammad Aminu Ahmad Page 103


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

Dictionary operations include the following:

• len(d) – number of items in d

• d[k] – item of d with key k

• d[k] = x – associate key k with value x

• del d[k] – delete item with key k

• k in d – test if d has an item with key k

• d.items() – a copy of the (key, value) pairs in d

• d.keys() – a copy of the list of keys in d

• d.values() – a copy of the list of values in d

9.4.10 Type Conversion


Integer and floating point data types can be converted to a string representation. String containing a number can also be converted
to a numeric data type. These can be achieved using the int(), float() and str() functions. For example:

To find the type of a variable, Python uses the type() function. For example:

9.4.11 Operator Precedence


When more than one operator appears in an expression, the order of evaluation depends on the rules of precedence as shown in the
following order:

Muhammad Aminu Ahmad Page 104


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

9.5 Executing Python Programs from File


The examples presented in the previous sections are executed in interactive mode. The interactive mode is useful when writing
small bits of code. To execute a python program or script with multiple lines of code, the program needs to be written and saved
in a file using an editor such as Notepad, Notepad++, vi, geany, gedit and many others. After choosing an editor, the Python
program can be written and saved as a .py file.
Consider the following example that displays “Welcome to Python Programming” using an editor and saves the file as
My_First_Script.py. Figure 9.1 shows the program written in Notepad++ and saved as My_First_Script.py in a subdirectory.
The program was then executed using the “python” command followed by the file name. The program then displayed “Welcome
to Python Programming”.

Figure 9.1: Writing and executing Python program using editor

9.6 Comments
As programs get bigger and more complicated, they become more difficult to read. Formal languages are dense, and it is often
difficult to look at a piece of code and figure out what the code is doing. For this reason, it is a good idea to add notes to your
programs to explain in natural language what the program is doing. These notes are called comments, and in Python they start
with the # symbol:

Everything from the # to the end of the line is ignored; it has no effect on the program. Comments are most useful when they
document non-obvious features of the code.

9.7 Input and Output


Python has input and output functions to read data and present the output of a program respectively; data can be taken from and
written to console or a file for future use.

9.7.1 Console Input and Output


Python provides the input() and print() functions to read data and present output on a console respectively. Inputs come from
various sources such as database, another computer, mouse click, file or network. This section discuss input from keyboard. The
input() function stops the flow of a program until the user provides an input and presses the return key. The input provided by
the user is returned as a string. If the input has to be transformed, such as numbers, we can use the casting(int(), float(), etc) or
eval() functions. Consider the following example:

1 name = input("Please enter your name: ")


2 age = eval(input("Please enter your age: "))
3 year = 2018
4 print("Your year of birth is " + str(2018-age) + ".")

Output

Muhammad Aminu Ahmad Page 105


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

The print() function always expects its arguments to be surrounded by parenthesis. The print function also use “\n” to indicate a
new line.
Python also provides a more sophisticated way of formatting output. The overall structure is that there is a string containing
format specifiers, followed by a percentage sign and a tuple that contains the variables to be printed in place of the format specifiers.
A string can contain format identifiers such as %f to format as a floats, %d to format as an integers and %s to format as a string.
Consider the following example:

1 from math import pi


2 print("Pi= %5.2f" % pi)
3 print("Pi = %10.3f" % pi)
4 print("Pi = %10.8f" % pi)
5 print("Pi = %d" % pi)
6 print("---------------")
7 print("Pi = %f, 142* pi = %f and pi ^2 = %f." % (pi ,142* pi ,pi **2))

Output

The format specifier of type %W.Df means that a Float should be printed with a total width of W characters and D digits behind
the decimal point. To print more than one object, provide multiple format specifiers and list several objects in the tuple.

9.7.2 Input and Output with Files


Python provides support for using files for data input and output. Python uses the open() function to open a file for input and
output operations. The open() functions returns a file object, and is most commonly used with two arguments: the file name and
mode of operation. The mode describes the way in which the file will be used; ’r’ when the file will only be read, ’w’ for writing
only (an existing file with the same name will be erased), ’a’ opens the file for appending and ’r+’ opens the file for both reading
and writing. Python assumes the mode to be ’r’ if it is omitted in the arguments.
Normally, files are opened in text mode, that means, you read and write strings from and to the file, which are encoded in a
specific encoding (the default being UTF-8). UTF-8 means “UCS Transformation Format - 8-bit”. UCS means Universal Character
Set. This is defined by International Standard ISO/IEC 10646. To open a file in binary mode, the letter ’b’ is appended to the
mode parameter. This will read and write data in the form of bytes objects. This mode should be used for all files that do not
contain text.

Reading Data from Files


Reading from a file involves four operations; a file object, linking the file object to a file using the open() function, using the file
object to read data and then closing the file using the close() function. The open() function takes the file name and creates a
Python file object. The file object is to read data from the file into the Python script. After reading data out of the file (via the
file object), the close() function is used to close the file, which disconnects the Python script from the file. Consider the following
example for reading data from a file. The file name is myfile.txt, which contains the following three lines of text:

This is the first line.


This is the second line.
This is a third and last line.

Muhammad Aminu Ahmad Page 106


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

1 input_file = open(’myfile.txt ’, ’r’)


2 text = input_file.read()
3 input_file.close()
4 print(text)

Output

The input_file is the file object used to read data from the file “myfile.txt” using the open() function. The input_file.read() function
reads the whole file, and returns it as one string (including new line characters). The object “text” references the content of the
data read from the file “myfile.txt”. The close() function is used to close the file and the print() function is used to output the
results of the read operation.
To read a particularly amount of the data, the read(size) function reads some amount of data and returns it as a string or bytes
object; size is an optional numeric argument. When size is omitted or negative, the entire contents of the file will be read and
returned. If the end of the file has been reached, the read() function will return an empty string (“ ”). The following example read
first 24 characters from the beginning of “myfile.txt”:

1 input_file = open(’myfile.txt ’, ’r’)


2 text = input_file.read(24)
3 input_file.close()
4 print(text)

Output

Another way of reading data from a file is using the readlines() function. The readlines() function returns a list of strings, where
each element of the list corresponds to one line in the file, that is, the readline() function reads the complete file into a list of strings.
Consider the following example:

1 input_file = open(’myfile.txt ’, ’r’)


2 text = input_file.readlines()
3 input_file.close()
4 print(text)

Output

The readlines() function is often used to iterate over the lines, and to do something with each line. For example:

1 f = open (’myfile.txt’, ’r’)


2 lines = f.readlines()
3 f.close()
4 for line in lines :
5 print("%d characters " % len(line ))

Output

Muhammad Aminu Ahmad Page 107


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

Writing Data to Files


Python uses the write(string) function to write the contents of string to a file. To write something other than a string, it needs to
be converted to a string first. Consider the following example:

1 output_file = open(’output.txt’, ’w’)


2 output_file.write("This is a test\n")
3 output_file.write(str(50))
4 output_file.close()

The output_file object is used to open the “output.txt” file for writing “w”. The output_file.write() function is used to write a
string data and a numeric data to the “output.txt” file. The output_file.close() is called to close the “output.txt” file and free up
any system resources taken up by the file.

9.8 Programming Examples


Let us now implement a Python program for the first two problems solved in Section 8.4.1. The first solution computes the weekly
earning of an employee while the second solution computer the price of a sales for a list of items bought.

9.8.1 Example 1
The following program calculates the weekly earning of an employee for a given number of hours and hourly rate after deducting
20 Naira as weekly tax.
Solution

Listing 9.1: Program to calculate weekly earning of employees


1 # A program that calculate the weekly earning of employee after deducting a task
2 # The program prints the results on the screen and keeps a record in a file.
3
4 employee_pay = open("Employee_Payments.txt", "a")
5
6 # input the number of hours worked, hourly rate and tax
7 hours_worked = eval(input("Please enter the number of hours worked: "))
8 hourly_rate = eval(input("Please enter the rate of payment per hour: "))
9 weekly_tax = eval(input("Please enter the weely tax: "))
10 employee_name = input("Please enter employee name: ")
11
12 #Process the weekly earning: Earning = (hours_worked * hourly_rate) - weekly_tax
13 earning = (hours_worked * hourly_rate) - weekly_tax
14
15 #Display the results on the screen
16 print("\n")
17 print("The payment for " + employee_name + " is " + str(earning) + " Naira\n")
18
19 # Keep record in a file
20 employee_pay.write("The payment for " + employee_name + " is " + str(earning) + " Naira\n")
21 employee_pay.close

Output

Muhammad Aminu Ahmad Page 108


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

9.8.2 Example 2
The following program calculates the final price of jewellery bought after deducting a discount of 30% and a payment of 13% tax
on the discounted price.
Solution

Listing 9.2: Program to calculate the price of jewellery


1 # A program that calculate the final price of jewellery bought
2
3 # input the price of jewellery
4 Price = eval(input("Please enter the price: "))
5
6 #Process the final price
7 finalPrice = (Price - (0.30 * Price)) + (0.13 * (Price - (0.30 * Price)))
8
9 #Display the results on the screen
10 print("\n")
11 print("The final price is " + str(finalPrice) + " Naira\n")

Output

9.8.3 Example 3
The following program computes the area of a triangle given the length of its sides: a, b, c.
Solution

1 # A program that calculate the area of a triangle


2
3 from math import sqrt
4
5 # input the length of the sides; A, B and C
6 a = eval(input("Please enter the length of side A: "))
7 b = eval(input("Please enter the length of side B: "))
8 c = eval(input("Please enter the length of side C: "))
9
10 s = (a+b+c)/2
11 #Process the area
12 area = sqrt(s * (s-a) * (s-b) * (s-c))
13
14 #Display the results on the screen
15 print("\n")
16 print("The area of the triangle is %.2f" % area)

Muhammad Aminu Ahmad Page 109


Chapter
10
Python Control Structures

10.1 Introduction
Commands in a program are processed from top to button. If the commands are given in the same line (separated by ;), then these
are processed from left to right (not suitable for good readability of the code.). However, we often need to execute instructions
by choosing one of different actions or run certain instructions repeatedly. Python uses different structures to control the flow of
instruction in a program; conditions and repetitions.

10.2 Conditions
Condition checking has always been the most basic and important construct in any language. Python provides conditional state-
ments in the form of if...else statement. The if statement allows conditional execution of code. The if-statement can also have an
else branch which is executed if the condition is wrong. The if-statement has the following structure:

1 if conditional1:
2 statement1
3 ...
4 statementn
5 elif conditional2:
6 statements
7 else:
8 statements

The if keyword is followed by a test: a Python expression that evaluates to a boolean. The line ends with a colon. The test line
is immediately followed by the block of code that is run if the test evaluates to True. Because it is a block of code it is indented
by four spaces to mark it as a block. This example has a single line, but the block can be as long as you want. This block is
sometimes called the “then-block”, because if the test is True, the instructios in the block is executed”. After the then-block comes
another new keyword, elif:. The elif (read as \else if") keyword allows checking for another condition when the first condition after
the if keyword results to False. After the elif: block comes another new keyword else:. This is not indented and is level with the
if to indicate that it is not part of the then block. It is then followed by a second block of code, known as the “else-block”. This
is the code that is run if the test evaluates as False. Again, because it is a block of code it is indented. The else keyword and its
corresponding block are optional. Nothing can be done if the test returns False. After the else-block the script continues. The
print line is unindented so is not part of the else-block. This line is run regardless of the result of the test.
Consider the following example:

110
Kaduna State University CSC101 Lecture Note: 2017-2018 Session

1 a = input("Enter a number \n")


2 if int(a) == 0:
3 print("The number is zero ")
4 elif int(a) < 0:
5 print("The number is negative ")
6 else:
7 print("The number is positive ")

Output

10.3 Looping
Looping is used to execute instructions repeatedly until a condition is satisfied. A loop has a number of components; before the
loop, within the loop and after the loop. The “before” and “after” sections are not part of the loop but they give context and may
use values needed by the loop. The loop itself must have some sort of test to indicate whether the loop should run again or whether
the looping can stop and control can pass to the “after” code. The body of the loop comprises the set of instructions that will be
run each time the loop repeats. Consider the following example for counting from 1 to 10:

Before the loop Number = 1

Loop test Number <=10

Yes
No Yes No

Print Number

Body of the loop


Number += 1

After the loop


Print “Done”

Figure 10.1: Looping Example

The “before” block initializes the name “Number” to a value 1; N umber = 1 The test determines whether “Number” is attached to
a value that is less than or equal to 10 (for final value); N umber <= 10, which evaluates to a boolean value. If the test evaluates to
True, then the body of the loop is processed; print the value of “Number” and increase it by one: print(number) and number+ = 1.
If the test evaluates to False, the program exits the loop and print “Done”.
Python uses For-loop and while-loop structures.

10.3.1 For Loop


The for-loop allows to iterate over a sequence (this could be a string or a list, for example). The structure of For loop in Python is:

1 for name in list:


2 statement1
3 statement2
4 ...
5 statementn

Muhammad Aminu Ahmad Page 111


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

The following example counts from 1 to 10 using For loop.

1 for Number in range(1,10):


2 print(str(Number))
3 print("Done")

Output

The for keyword is followed by a test, Number in range(1, 10), and a colon to indicate the end of the test in the line. The function
range() provides a list of objects as specified in the parameters, which in the case of the above example is 1 to 10. The for keyword
tells Python that there is a for loop. If the test evaluates to True, the result is printed otherwise the program exits the for loop
and print “Done”. The loop body is indented four spaces.
The for-loop also allows iteration over a sequence. for example:

1 programmes = [’Accounting’, ’biology’, ’chemistry’, ’Computer Science’, ’Physics’]


2 for program in programmes:
3 print(program.upper())
4 print ("DONE")

Output

10.3.2 While Loop


The structure of the while loop in Python is:

1 while conditional:
2 statement1
3 statement2
4 ...
5 statementn

The while keyword is followed by a test and a colon, then the loop body being indented four spaces. The following example counts
from 1 to 10 using while loop.

1 Number = 1
2 while Number <= 10:
3 print(str(Number))
4 Number += 1
5 print("Done")

Muhammad Aminu Ahmad Page 112


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

Output

The test expression is preceded with the Python keyword while. This is what tells Python that there’s a loop coming. It must be
directly followed by an expression that evaluates to a Boolean; Number <=10. The test is followed by a colon to indicate the end
of the expression on the line. Note that the test evaluates to True for the loop to be run and False for the loop to quit. The test is
“shall the loop keep going” not “shall the loop stop”.
The loop body, the code that is repeated, appears on the lines following the “while line”. Both its lines are indented by four
spaces each. Note that the “after” section, print(“Done”) is not indented. Here is another program that uses while loop to compute
interest for 15 years:

1 balance = 1000 # in Naira


2 rate = 0.05 # 5% interest
3 years = 0
4 while years < 15: # repeat until 2000 Naira is reached
5 interest = balance * rate
6 balance += interest
7 years = years + 1
8 print(’You need ’, years, ’years to reach ’, int(balance) , ’Naira.’)

Output

10.3.3 Break and Continue


Python uses the break and continue to exit a loop immediately or skip to next loop iteration respectively. Consider the following
examples:

1 x = 3
2 while x < 10:
3 if x > 7:
4 x += 2
5 continue
6 x = x + 1
7 print("Still in the loop.")
8 if x == 8:
9 break
10 print("Outside of the loop.")

Output

Muhammad Aminu Ahmad Page 113


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

1 for x in range(10):
2 if x > 7:
3 x += 2
4 continue
5 x = x + 1
6 print("Still in the loop.")
7 if x == 8:
8 break
9 print("Outside of the loop.")

Output

10.4 Programming Examples


Let us now consider some programming examples.

Example 1
The following program dertermined the salary of employees of a company. The employees in department B, C and D recieved 8%
salary increase, but the employees in department A (that performed the best) receive an increase of 10%.
Solution

Listing 10.1: Program to calaculate salary increase


1 # A program that calculate the salary of employees in a department
2 # The program prints the results on the screen
3
4 # input the salary and department
5 salary = input("Please enter the current salary: ")
6 department = input("Please enter the department: ")
7
8 #calculate the new salary
9 while(True):
10 if (department.upper() == "A"):
11 new_salary = int(salary) + (0.1 * int(salary))
12 break
13 elif(department.upper() == "B") or (department.upper() == "C"):
14 new_salary = int(salary) + (0.08 * int(salary))
15 break
16 else:

Muhammad Aminu Ahmad Page 114


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

17 print("department ID is incorrect")
18 department = input("Please enter the department: A, B or C?")
19
20
21 #Display the results on the screen
22 print("\n")
23 print("The new salary is " + str(new_salary) + " Naira\n")

Output

Example 2
The following program calculates the monthly commision of a salesperson and net income of the company. A salesperson earns 7%
monthly commission on 2000 Naira sales income, a 10% commission on sales income over 2000 Naira but less than or equal to 5000
Naira, and 15% commission on sales income above 5000 Naira.
Solution

1 # A program that calculate the commission of a sales person and net income of the company
2 # The program prints the results on the screen
3
4 # input the monthly sales
5 sales = eval(input("Please enter the monthly sales amount: "))
6
7 #calculate the commission and net income
8 if (sales == 2000):
9 comm = 0.07 * sales
10 net_income = sales - comm
11 elif(sales > 2000) and (sales <= 5000):
12 comm = (0.07 * sales) + (0.1 * (sales-2000))
13 net_income = sales - comm
14 elif(sales > 5000):
15 comm = (0.07 * sales) + (0.1 * (sales - 2000)) + (0.15 * (sales - 5000))
16 net_income = sales - comm
17 else:
18 comm = 0
19 net_income = sales
20
21 #Display the results on screen
22 print("\n")

Muhammad Aminu Ahmad Page 115


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

23 print("The commission is %.2F Naira" % comm )


24 print("The net income is %.2f Naira" % net_income)

Output

Example 3
A company pays each salesperson a commission of 20% based on the total number of sales made by the person. The following
program calculates the commission on the sum of the sales for each of the salespeople working for the company. The program also
calculates the total sales, total commission on sales of all salespersons, average sales and the highest and lowest sales.
Solution

1 # A program that calculate the commission, total, average. highest and lowest sales
2 # The program prints the results on the screen
3
4 #variables declaration
5 minSale=maxSale=averageSale=averageComm=count=totalSales=totalComm = 0
6 i = 1
7 commList = [] #list of commission for salespersons
8
9 # Input and output files
10 mySales = open("sales.txt", "r")
11 myComm = open("comm.txt", "a")
12
13 sales = eval(mySales.read()) #get inputs from sales.txt file
14
15 #Print a list of sales from sales.txt file on the screen
16 saleValues = list(sales)
17 print("\nList of sales from sales.txt file\n")
18 print("S/N Sales")
19 for val in saleValues:
20 print(str(i) + "\t" + str(val))
21 i += 1
22
23 #calculate the commission, total, average highest and lowest sales
24 i = 1
25 maxSale = minSale = saleValues[0]
26 for sale in saleValues:

Muhammad Aminu Ahmad Page 116


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

27 count += 1
28 comm = 0.2 * sale
29 totalSales += sale
30 totalComm += comm
31 commList.append(comm)
32 if (sale > maxSale):
33 maxSale = sale
34 if(sale < minSale):
35 minSale = sale
36 if (count != 0):
37 averageSale = totalSales/count
38 averageComm = totalComm/count
39
40 #Display the results on screen
41 print("\n")
42 print("LIST OF COMMISSIONS\n")
43 for comm in commList:
44 print(str(i) + " %.2F" % comm)
45 i+=1
46 print("\nSUMMARY\n")
47 print("Total Sale = %.2f" % totalSales)
48 print("Average Sale = %.2f" % averageSale)
49 print("Total Commission = %.2f" % totalComm)
50 print("Average Commission = %.2f" % averageComm )
51 print("Highest Sale = %.2f" % maxSale)
52 print("Lowest Sale = %.2f" % minSale)
53
54 #keep record in comm.txt file
55 i = 1
56 myComm.write("LIST OF COMMISSIONS\n")
57 for comm in commList:
58 myComm.write(str(i) + " %.2F\n" % comm)
59 i+=1
60 mySales.close()
61 myComm.close()

Output

Muhammad Aminu Ahmad Page 117


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

Muhammad Aminu Ahmad Page 118


Chapter
11
Python Functions and Modules

11.1 Introduction
Functions enable the grouping a number of statements into a logical block. Functions are used through a clearly defined interface,
by providing certain parameters to the function and receiving some information back. For example the print(string) function prints
the text in the object string. However, we do not know how exactly it prints the text, but we know that if we pass a string into
the function, it will print the text on a console. Functions provide the basic building blocks of functionality in larger programs,
and help to control the inherent complexity of the process. This abstraction is useful because it breaks down a system into smaller
components that all work together through well defined interfaces, but which do not need to know about the internal realisations
of each other’s functionality. Functions provide the basic building blocks of functionality in larger programs and help to control
the inherent complexity of the process.

11.2 Using Functions


Functions, such as the print(), input(), eval(), int(), float(), range() and type() have been used in the previous chapters. The
Python standard library includes many other functions useful for common programming tasks. Let us consider some functions in
math and time modules. The standard math module provides the functionality of a scientific calculator, the time package contains
a number of functions that relate to time. The functions in a module can be viewed using the dir() function:

11.3 Creating Functions


The word “function" in programming refers to a named sequence of operations that perform a computation. For example, the
function sqrt() which is defined in the math module computes the square root of a given value:

119
Kaduna State University CSC101 Lecture Note: 2017-2018 Session

The value passed to the function sqrt() is 9. This value is called the argument of the function. A function may have more than
one argument. The function returns the value 3.0 (the result of its computation) to the “calling context". This value is called the
return value of the function. It is common to say that a function takes an argument and returns a result or return value. The
generic format of a function definition is:

1 def name([arg1, arg2, ...]):


2 statement1
3 ...
4 statementn
5 return [expression]]

The Python keyword to define a function is “def”. This is followed by the name of the function. The name of the function is
followed by a pair of round brackets, which contains all the input values for the function. The colon marks the end of the line
and the beginning of the body of the function. In Python, a colon at the end of a line is always followed by an indented block of
code. This will be the body of the function that defines what the function actually does with the input(s) it is given. Finally we
need to specify exactly what value the function is going to return. We do this with another Python keyword, “return”. The value
that follows the return keyword is the value returned by the function. When Python reaches the return statement in a function
definition it hands back the value and ends the execution of the function body itself. Consider the following example:

1 def square (x):


2 return x * x
3
4 for i in range (5):
5 i_squared = square (i)
6 print("%s * %s = %d" % (i, i, i_squared))

Output

The keyword def tells Python that we are defining a function names square. The function takes one argument, x and returns the
value x2 . Lines 1 and 2 defined the function square(). Lines 4 to 6 defines the main program that uses the function square(). The
main program uses the range() function to print a table of squared numbers from 0 to 4.
A function can have more than one argument as shown in the following example:

1 def add(numbers):
2 sum_so_far = 0
3 for number in numbers:
4 sum_so_far += number
5 return sum_so_far
6
7 myNumbers = eval(input("Please enter two or more numbers separate by comma: "))
8 MyListOfNumbers = list(myNumbers)
9 print("The sum is %s" % (add(MyListOfNumbers)))

Output

Muhammad Aminu Ahmad Page 120


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

The function add() takes two or more numerical values in form of a list and return their sum (lines 1 to 5). The main program
takes a list of numbers from a user as input. The eval() function is used to convert the values from string to numeric data and
assigned the result to the variable myNumbers. The values entered are converted to a list using the list(myNumbers) function
and assigned to the variable MyListOfNumbers. The add function uses the MyListOfNumbers variable to compute the sum of the
numbers, which is then presented on the screen by the print() function.

11.4 Variable Scope


Variables that are defined within functions are called local variables. Local variables have the following properties:

• The memory required to store a local variable is used only when the variable is in scope. When the program execution
leaves the scope of a local variable, the memory for that variable is freed up and can be used for a local variable in another
function when that function is invoked.

• The same variable name can be used in different functions without any conflict. The interpreter derives all of its information
about a local variable used within a function from the definition of that variable within that function. When executing
code in one function, the interpreter will not look for a variable definition in another function. Thus, there is no way a local
variable in one function can interfere with a local variable declared in another function.

A local variable is transitory, so its value is lost between function invocations. However, sometimes it is desirable to have a variable
that lives as long as the program is running; that is, until the main function completes. This type of variable can be defined outside
of all functions so that any function can access and modify the variable. A global variable is declared outside of any function within
a program. Python uses the keyword global to specify a global variable within a function.

11.5 Modules
Multiple Python functions can be defined in one file. A Python module is a group of variables and functions defined in a separate
file, which enables the creation of libraries of functionalities. Python provides modules that contains a large number of functions.
A programmer can extend the capabilities of Python by importing modules or packages using an import statement. There are
several variations on the use of import. For example, a programmer can import an entire module:

A programmer can also import the desired components of a module:

A module is simply a .py file. Thus, modules can be created that contain a collection of functions or other objects. Let us consider
an example.
Example
Write Python functions that evaluate the following polynomials for a given value of x

f (x) = 2x6 − 13x5 + 75x3 + 2x2 − 60

f (x) = 3x6 − 15x5 + 10x3 + 3x2 − 40

f (x) = 2x3 + 9x2 + 7x − 6

Solution
Listing 11.1 shows a python module containing three functions for solving each of the polynomials.

Muhammad Aminu Ahmad Page 121


Kaduna State University CSC101 Lecture Note: 2017-2018 Session

Listing 11.1: Python file containing polynomial function


1 # Functions to evaluate a polynomials for a given value of x
2
3 from math import pow
4
5 # The function definition
6 def polynomial1(x):
7 f = (2*pow(x, 6)) - (13*pow(x, 5)) + (75*pow(x, 3)) + (2*pow(x, 2)) - 60
8 return f
9
10 def polynomial3(x):
11 f = (3*pow(x, 6)) + (15*pow(x, 5)) - (10*pow(x, 3)) - (3*pow(x, 2)) + (15*x) - 40
12 return f
13
14 def polynomial2(x):
15 f = (2*pow(x, 3)) + (9*pow(x, 2)) + (7*x) - 60
16 return f

Listing 11.2 shows a python program that takes user input and evaluate the polynomials using the functions defined in the
polynomial module.

Listing 11.2: Python program that uses the polynomial functions


1 from polynomials import *
2
3 x = eval(input("Please enter the value of x :"))
4 print("The value of polynomial 1 is %.2f\n" % polynomial1(x))
5 print("The value of polynomial 2 is %.2f\n" % polynomial2(x))
6 print("The value of polynomial 3 is %.2f\n" % polynomial3(x))

Muhammad Aminu Ahmad Page 122

You might also like