Computer Science Notes
Computer Science Notes
Introduction
Calculations have always been part of man's life. Simpler calculations take less time
but complex calculations take much longer time. With the idea of developing a machine
which could perform complex calculations faster and with full accuracy, man invented the
‘computer’. Computer is derived from the word “compute” which means “calculate” meaning
that a computer is simply a calculating machine.
Definition: A computer is an electronic device that can accept, store, and process data to
produce information. It can also be defined as a machine that can take instructions and perform
computations based on those instructions.
Computers range from very small to very large machines with some capable of doing
millions of calculations in a single second, while others may take long periods of time to do even
the most simple calculations.
1. Classification of Computers
Computers can be classified into five categories, on the basis of their size and capabilities.
The size of the computer may refer to multiple factors like, size of the memory, number of
terminals that can be connected to the computer, storage capacity of the hard disk and the type
of processor used in the computer. These categories are supercomputers, mainframe computers,
minicomputers and microcomputers.
1.1. Microcomputers
Microcomputers are the smallest category of computers that range in size from
servers to handheld devices. They are the type of computers meant for public use. They are
designed to be used by one person at a time. Microcomputers, also called personal computers
(PC), can be further classified into desktop computers, laptop computers. Tablet PCs and
personal digital assistants (PDAs).
1.2. Minicomputers
Minicomputers are larger and faster than microcomputers and are designed to
support more than one user at a time. They are generally used for processing large volumes
of data in an organization. Minicomputers are also used as servers in a local area network.
Another name for minicomputers is “mid-range computers.” Two classic examples of
minicomputers were the Digital Equipment Corporation VAX and the IBM AS/400.
1
Advanced Level Computer Science/ICT
capacities. They are used by large organizations like meteorological surveys and statistical
institutes for performing bulk mathematical computations.
1.4. Supercomputers
Supercomputers are the fastest and most expensive type of computers. They can
perform hundreds of millions of computations per second and are employed for specialized
applications that require immense amounts of mathematical calculations. Weather
forecasting, scientific simulations, nuclear energy research, electronic design, and analysis of
geological data all require supercomputers. Examples of supercomputers are Fujitsu K
computer, IBM Blue Gene, Cray Jaguar and NEC Earth Simulator.
2. Generations of Computers
Computers of specific electronic era are often referred to as a generation. Each generation
is characterized by a major technological development that fundamentally changed the way
computers operate, resulting in increasingly smaller, cheaper, more powerful and more efficient
and reliable devices.
2
Advanced Level Computer Science/ICT
Second generation computers moved from cryptic binary machine language to symbolic, or
assembly languages, which allowed programmers to specify instructions in words. High-level
programming languages were also being developed at this time, such as early versions of COBOL
and FORTRAN. These were also the first computers that stored their instructions in their memory,
which moved from a magnetic drum to magnetic core technology.
3. Applications of Computers
Computers are fast becoming our way of life and one cannot imagine life without computers in
today’s world. Their importance can be attributed to the fact that almost every sphere of our life is
affected. We find their applications particularly in fields where computations are required to be
done at a very fast speed and where data is so complicated that the human brain finds it difficult to
cope up with.
3
Advanced Level Computer Science/ICT
a public space without the need for a cashier, human clerk or bank teller. The ATM can be used by
the customers to make cash withdrawals, credit card advances or check their account balances.
On most modern ATM systems, a customer is identified by inserting a plastic ATM card with
a magnetic stripe or a plastic smart card with a chip, which contains a unique card number and
some security information. Authentication is provided by the customer entering a personal
identification number (PIN). Upon successful entry of the PIN, the customer may perform a
transaction.
ATMs are known by various other names including automatic/automated banking machine
(ABM), automated transaction machine and cashpoint.
Definition: A stock control system is basically a database that keeps track of stock and informs users of
when to re-order along with helpful sales reports.
When items are sold or delivered, their codesare input to the system either manually or using a
point-of-sale terminal (barcode scanner or similar technology). The database matches the codes
with the items’ names and prices, prints an itemized bill and uses the data to update stock levels. It
also updatesa sales file which can be used there and then to calculate all sorts of statistics.
Stock control systems make it very easy for stock levels to be monitored, and for stock to be
reordered when it is running low.
4
Advanced Level Computer Science/ICT
activities. They allow users to book hotel rooms, buy airline tickets, rent cars, etc. They also provide
access to railway reservations and bus reservations in some markets, although these are not always
integrated with the main system.
Definition: A computer model is a computer program that represents the construction and working of
a real-life situation or system.
Models are usually produced in order to study the systems they represent.
Definition: Simulation is the manipulation or operation of a model of a system in order to study the
behavior of the real system.
Modeling and simulation are useful for studying systems which would be impossible, too expensive
to build, impractical or dangerous to work with. Examples of situations that can be simulated are:
The training of pilots
The design of a bridge
The design of a building
5
Advanced Level Computer Science/ICT
6
Advanced Level Computer Science/ICT
3.3.3. Robotics
Robotics is the branch of technology that deals with the design, construction, operation and
application of robots. A robot is a machine that is designed to repeatedly do what humans can do
with speed and precision. An important application of this technology has been to create robots to
perform certain functions that are dangerous for human beings, or to do tasks that can be more
effectively performed by machines than by people. Although it may not have the physical
appearance of a human being, a robot may be thought of as a machine acting as a person while being
controlled by a computer.
b. Recording Software
Recording software make it possible to record sound using a computer. With recording software,
users can record their own music without going to Record Label Companies. Recording software
makes it easy to fix poor recording. Also, one program can perform the same number of actions that
will be performed with a number of equipment. Protools, Adobe Audition, Cool Edit Pro and Cubase
are common examples.
d. Advertising
Artists use the Internet to advertise new CD releases, tour dates, merchandise, and bonus tracks.
Samples of new songs are released to entice the listener to buy the album.
7
Advanced Level Computer Science/ICT
Answer: A form of stop-motion animation in which each object is sculpted in clay or a similarly pliable
material such as plasticine.
b. Motion Capture
Motion capture (mocap) is the process of recording a live motion event and translating it into
actionable data that allows for a 3D recreation of the performance. In film making, motion capture is
used to film an actor’s movements which are turned into 3D movements, and then mapped to an
avatar.
Introduction
Computers have had many effects on individuals in society. They have impacted on the way
individuals work, socialize and run their lives. As a result of computers, an individual's values are
now in constant flux. The moral and ethical framework that guides an individual is constantly
changing as is the economic and legal framework within which lives are led.
8
Advanced Level Computer Science/ICT
2. Computer Crimes
A computer crime is any illegal act that involves the computer either as the target of the crime or as
a tool used in committing the crime. When the computer is the target of the criminal act, the crime is
said to be a computer-related crime. When it is a tool used to commit the crime, the crime is
referred to as a computer-assisted crime.
Virus
A virus is a computer program that can copy itself and infect a computer where it destroys files and
disrupts the operation of the computer. A virus can spread from one computer to another (in some
form of executable code) when its host is taken to the target computer.
Worm
A worm is a self-replicating malicious program which uses a computer network to send copies of
itself to other computers (nodes) on the network and it may do so without any user intervention.
9
Advanced Level Computer Science/ICT
Unlike a virus, it does not need to attach itself to an existing program. Worms cause harm to the
network by consuming bandwidth whereas viruses corrupt or modify files on a targeted computer.
Trojan horse
A Trojan horse is malware that appears to perform a desirable function for the user prior to run or
install but instead facilitates unauthorized access of the user's computer system. Once a Trojan
horse has been installed on a target computer system, a hacker may have access to the computer
remotely and perform various operations, limited by user privileges on the target computer system
and the design of the Trojan horse.
Spyware
Spyware is software that monitors a computer user’s activity without their knowledge and reports
it to a central location. The purpose of spyware ranges from purportedly benign (enforcing
copyrights, displaying targeted advertisements) to very malicious (stealing passwords and credit
card numbers).The most common way to get spyware on your computer is to install it yourself
when you are tricked into installing free software.
Logic bomb
A logic bomb also known as slag code, is a piece of computer code that executes a malicious task
such as clearing a hard drive or deleting specific files, when it is triggered by a specific event. It is
secretly inserted into the code of a computer's existing software, where it lies dormant until that
event occurs. This event may be a specific date and time or failure to input a command at a certain
time.
10
Advanced Level Computer Science/ICT
Other types of crimes are: scamming, theft of computer equipment, pharming, spoofing, and
phreaking.
11
Advanced Level Computer Science/ICT
Integrity ensures that information is not altered by unauthorized persons in a way that is not
detectable by authorized users. That means that there is an external consistency in the system
- everything is as it is expected to be.
Availability ensures that the system is accessible and useable upon appropriate demand by
authorized users. In other words, this means preventing denial-of-service.
Different mechanisms used to ensure the security of computer systems are authentication,
encryption, firewalls, digital signatures, etc.
3.1. Authentication
Authentication is the process of determining if someone is who they declare to be. In simple terms,
it is proving someone’s identity. Authentication can be obtained by the user providing something
they know (password), something they have (smart card) or something they are (biometrics).
3.1.1. Passwords
A password is a secret sequence of characters that is required to login to a system, thus preventing
unauthorized persons from gaining access to the system. When authentication is done through the
use of a password, knowledge of the password is assumed to guarantee that the user is authentic.
Passwords can be guessed or cracked and so if anyone is using a password to protect their system,
the following guidelines will help make it more secure:
Don’t choose an obvious password (like your name, date of birth or name of relative)
Keep your password secret. Don’t share it!
Change your password regularly but not too often.
Make your password at least eight characters long.
Do not use common or proper words of phrases - these can be found using a dictionary cracker.
Use a mixture of upper and lower case letters and numbers.
3.1.3. Biometrics
Biometrics is the science and technology of measuring and analyzing biological data. In computer
security, it refers to the use of measurable biological characteristics such as fingerprints, eye retinas,
iris patterns, facial patterns, voice patterns, hand measurements and DNA, to identify a person. It is
the safest authentication technique.
Answer: The limitation and control of access to a system through identification and authentication.
Or
12
Advanced Level Computer Science/ICT
The process of limiting access to a system only to authorized users. This can be achieved through
identification and authentication.
3.2. Encryption
Encryption is the process of transforming a message using an algorithm into a form unreadable by
anyone except the intended recipient. The original message is known as plaintext, the algorithm is
cipher and the encrypted text is ciphertext. To read an encrypted message, one must have access to
a key that will enable them to decrypt it.
Encryption ciphers can be grouped into two: substitution and transposition ciphers.
Sender Recipient
Hello Encrypted text Hello
%fd$h
Encryption Decryption
Key Key
Encryption
13
Advanced Level Computer Science/ICT
Suppose k = 3
Plain text letter: ABCD… WXYZ
Cipher text letter: DEFG…ZABC
ABCDEFGHIJKLMNOPQRSTUVWXYZ
BCDEFGHIJKLMNOPQRSTUVWXYZA
CDEFGHIJKLMNOPQRSTUVWXYZAB
DEFGHIJKLMNOPQRSTUVWXYZABC
EFGHIJKLMNOPQRSTUVWXYZABCD
FGHIJKLMNOPQRSTUVWXYZABCDE
GHIJKLMNOPQRSTUVWXYZABCDEF
HIJKLMNOPQRSTUVWXYZABCDEFG
IJKLMNOPQRSTUVWXYZABCDEFGH
JKLMNOPQRSTUVWXYZABCDEFGHI
KLMNOPQRSTUVWXYZABCDEFGHIJ
LMNOPQRSTUVWXYZABCDEFGHIJK
MNOPQRSTUVWXYZABCDEFGHIJKL
NOPQRSTUVWXYZABCDEFGHIJKLM
OPQRSTUVWXYZABCDEFGHIJKLMN
PQRSTUVWXYZABCDEFGHIJKLMNO
QRSTUVWXYZABCDEFGHIJKLMNOP
RSTUVWXYZABCDEFGHIJKLMNOPQ
STUVWXYZABCDEFGHIJKLMNOPQR
TUVWXYZABCDEFGHIJKLMNOPQRS
UVWXYZABCDEFGHIJKLMNOPQRST
VWXYZABCDEFGHIJKLMNOPQRSTU
WXYZABCDEFGHIJKLMNOPQRSTUV
XYZABCDEFGHIJKLMNOPQRSTUVW
YZABCDEFGHIJKLMNOPQRSTUVWX
ZABCDEFGHIJKLMNOPQRSTUVWXY
14
Advanced Level Computer Science/ICT
Example:
For the message COMPUTING GIVES INSIGHT and keyword TRUE, we proceed by repeating the
keyword as many times as needed above the message, as follows.
T R U E T R U E T R U E T R U E T R U E T
C O M P U T I N G G I V E S I N S I G H T
The Vigenere tableau above can be used directly to encode the message. For each letter of the
message use the letter of the keyword to determine a row and go across the row to the column
headed by the corresponding letter of the message. The letter at the intersection is used to replace
the letter of the message.
a. Columnar Transposition
A columnar transposition cipher enters the plaintext into a rectangle of a predetermined width and
extracts cipher text by columns from left to right.
Example 1:
Plaintext: ENJOY THE BEAUTY OF SCIENCE
E N J O Y
T H E B E
A U T Y O
F S C I E
N C E
Example 2:
Key: ORANGE
Plaintext: THE FUTURE IS BRIGHT
O R A N G E
T H E F U T
U R E I S B
15
Advanced Level Computer Science/ICT
R I G H T
Example 1:
Plaintext: WE ARE HAVING FUN R N
A E I G
E H V F N
Cipher text: RN AEIG EHVFN W A U WAU
Example 2: S L
Cipher text: SL IIIFE HSAEC TRN I I I F E
H S A E C
Plaintext: THIS IS RAIL FENCE T R N
3.3. Firewall
A firewall is a system designed to prevent unauthorized access to or from a private network.
Firewalls are implemented in either hardware or software form, or a combination of both. They
prevent unauthorized Internet users from accessing private networks connected to the Internet. All
messages entering or leaving the network must pass through the firewall which examines each
message and blocks those that do not meet the specified security criteria. Some Operating Systems
like Windows XP, 7 and Mac OS X, have built-in firewalls.
16
Advanced Level Computer Science/ICT
4. Computer Ethics
Ethics refers to the principles of right and wrong that individuals, acting as free moral agents, use to
make choices that guide their own behavior. Ethical principles place a value on human acts
according to whether they are good or bad.
Computer ethics refers to standards of good conduct applied within the use of computers. It defines
principles for judging computing acts whether they are good or bad.
17
Advanced Level Computer Science/ICT
2.1. Strive to achieve the highest quality, effectiveness and dignity in both the process and products
of professional work.
2.2. Acquire and maintain professional competence.
2.3. Know and respect existing laws pertaining to professional work.
2.4. Accept and provide appropriate professional review.
2.5. Give comprehensive and thorough evaluations of computer systems and their impacts,
including analysis of possible risks.
2.6. Honor contracts, agreements, and assigned responsibilities.
2.7. Improve public understanding of computing and its consequences.
2.8. Access computing and communications resources only when authorized to do so.
1. To accept responsibility in making decisions consistent with the safety, health and welfare of the
public, and to disclose promptly factors that might endanger the public or the environment;
2. To avoid real or perceived conflicts of interest whenever possible, and to disclose them to affected
parties when they do exist;
3. To be honest and realistic in stating claims or estimates based on available data;
4. To reject bribery in all its forms;
5. To improve the understanding of technology, its appropriate application, and potential
consequences;
6. To maintain and improve our technical competence and to undertake technological tasks for
others only if qualified by training or experience, or after full disclosure of pertinent limitations;
7. To seek, accept, and offer honest criticism of technical work, to acknowledge and correct errors,
and to credit properly the contributions of others;
8. To treat fairly all persons regardless of such factors as race, religion, gender, disability, age, or
national origin;
9. To avoid injuring others, their property, reputation, or employment by false or malicious action;
18
Advanced Level Computer Science/ICT
4.3. Netiquette
Netiquette is short for network etiquette. It is a set of rules about acceptable behavior when
communicating over the Internet. Some basic rules of netiquette are:
Avoid flaming i.e. using obscene or inappropriate language in your emails or posts
Avoid using capital letters in your emails/comments, it is considered like YOU ARE
SHOUTING and it is harder to read.
Avoid sloppiness i.e. avoid spelling and grammatical errors. Re-read and edit your
emails/comments before you send/post
Do not send huge file attachments unless they are requested
Always fill the subject field of an email before you send
Do not format your emails with colored text or background color. They may cause them hard
to read.
5. Legislation
Legislation is the act of making and passing laws.Some laws that govern the use of computers area
the Data Protection Act, the Computer Misuse Act, the Copyright, Design and Patent Act, and the
Health and Safety Act.
19
Advanced Level Computer Science/ICT
Copyrightis a statutory grant that protects original work. Something that is copyrighted is not
to be reproduced, published or copied without permission from the copyright holder. Ideas are
not protected by copyright; only the specific presentation of the idea is copyrightable.
A Patentis a grant to inventors that give them exclusive monopoly over their invention. It gives
them the right to stop others from producing, selling or using their invention. Unlike
copyrights, patents protect the ideas or design of the invention rather than any tangible form
of the invention.
Answer:
i) Digital inclusion
Digital inclusion is commonly defined asthe incorporation of information technologies into the
community in order to promote education and improve the quality of life.
In other words, it is the ability of individuals and groups to access and use information and
communication technologies.
20
Advanced Level Computer Science/ICT
Digital inclusion is necessary as we move towards a technology based society to ensure that all
individuals can participate fully in the economic, educational, civic and social activities of their
community.
6.2. Ergonomics
Ergonomics refers to the application of scientific knowledge to the workplace in an effort to
improve the well-being and efficiency of workers. Simply put, it is the study of human factors
related to things people use. These factors include workstation layout, sitting posture, lighting,
viewing distance etc.
21
Advanced Level Computer Science/ICT
c. Placement of components
Placing components e.g. mouse, telephone, far away from you can cause you to repeatedly reach out
for them resulting in strain on the shoulder, arm and neck.
Regardless of how good your working posture is, working in the same posture or sitting still for
prolonged periods is not healthy. You should change your working position frequently by
Making small adjustments to your chair or backrest
Stretching your fingers, arms and torso
Walking around a few minutes periodically
6.2.3. Lighting
When a computer work environment is planned both overall lighting and positioning of lights and
windows must be considered. Overhead lights and windows are sources of glare that may mask
22
Advanced Level Computer Science/ICT
whatever is shown on the screen resulting in visual fatigue and discomfort. There are three types of
glare: direct, indirect and masking.
Direct glare occurs when there are bright light sources directly in the operator’s field of view.
Windows are often a source of direct glare.
Indirect glare occurs when light from windows or overhead lights is reflected off shiny surfaces
in the field of view.
Light from sources directly overhead causes masking glare on the screen.
The use of light absorbing blinds and curtains will help reduce both direct and indirect glare. Placing
the monitor in an appropriate position can help reduce overhead or masking glare. Glare can also be
prevented using an anti-glare screen filter.
Introduction
Computer architecture refers to those attributes of a system that have a direct impact on thelogical
execution of a program like the instruction set, the number of bits used to represent various data
types, I/O mechanisms and techniques for addressing memory.
On the other hand, computer organization refers to the operational units of the system and their
interconnections that realizethe architectural specifications like control signals, interfaces between
computer and peripherals and the memory technology used.
So, for example, the fact that a multiply instruction is available is a computer architectureissue. How
that multiply is implemented is a computer organization issue.
Programs being stored in memory ensures that by altering the stored program, the computer can
perform a different task – reason why a computer is called a general purpose machine.
Neumann divided the computer into four functional units: input, processing, storage and output.
Control Unit
Input Unit Output
Arithmetic
Logic Unit
Primary 23
Storage
Advanced Level Computer Science/ICT
Assignment: What is the difference between a computer with a Von Neumann’s architecture and one
with a Harvard architecture?
1.1.1. Keyboard
The keyboard is the standard input device attached to computers. It has keys (buttons) that are
pressed to enter data and commands into the computer. These keys represent letters, numbers,
symbols and control characters. The keyboard has a total of 101-104 keys divided into different
groups or keypads.
Function keys, labeled F1-F12, perform specific functions based on the software used. F1 for
example is used in most software to display help.
Alphabetical keys
Numerical keys
Navigation keys also called direction keys are used to navigate through documents and
websites. Examples of navigation keys are the up, down, left and right arrows.
Action keys
There are different keyboard layouts but the best known are QWERTY mainly used by English
speakers and AZERTY used by French speakers. Another keyboard layout modified greatly from a
standard layout is DVORAK, devised to increase typing speed by placing frequently used keys more
naturally.
A keyboard connects to the computer through cable PS/2 cable, USB cable or wireless (cordless).
24
Advanced Level Computer Science/ICT
1.1.2. Mouse
A mouse is a handheld device which is moved across a flat surface to control the movement of a
pointer on a computer screen. The mouse has two buttons, the right and the left buttons, which are
clicked (pressed)to enter commands into the computer.
Different actions that can be performed with a mouse are:
Click: Pressing the left mouse button.
Right-click: pressing the right mouse button
Double-click: pressing the left button two times in quick succession
Drag: pressing the left button and while holding, moving the mouse
Drop: Releasing the left button after dragging
Drag and drop can be used to move files or documents from one place to another.
A mouse connects to a computer through PS/2 cable (PS/2 mouse), USB cable (USB mouse), or
wireless (optical mouse).
1.1.3. Scanner
A scanner is an optical device that converts hardcopy image or text into digital form so that it can be
fed into the computer. The common optical scanner devices are the flatbed scanner, optical mark
reader, optical character reader and barcode reader.
Flatbed Scanner: a scanner in which the object to be scanned is held flat against a piece of glass.
Optical Mark Reader
Optical Character Reader
Barcode Reader
Other types of input devices are joystick, light-pen, trackball and touch pad.
1.2.1. Monitor
Also referred to as VDU (Visual Display Unit), the monitor is the most popular output device. It
displays information generated by a computer on a screen. Such output is known as softcopy output.
Monitors are characterized by the technology they use and their resolution.
By the technology used, monitors are of two main types: Cathode Ray Tube (CRT) monitors and
Flat Panel Display.
o CRT monitors are similar to a television set.
o Flat panel display monitors are of different types: Liquid Crystal Display (LCD),
Electroluminescent Display (ELD), Gas Plasma (GP) and Thin Film Transistor (TFT) monitors.
25
Advanced Level Computer Science/ICT
Monitor resolution refers to the number of dots (pixels) on the screen. It is expressed as a pair
of numbers that give the number of dots on a line (horizontal) and the number of lines
(vertical). The size of a pixel is known dot pitch. The smaller the dot pitch, the clearer and
sharper the picture appears on the monitor. Most monitors come with a .28 dot pitch.
1.2.2. Printer
A printer is a device that produces computer-generated information on paper. Such output is
referred to as printout or hardcopy. Based on the technology used, printers can be classified into
impact and non-impact printers.
Impact printers have mechanical contact between paper and printing head (e.g. daisy wheel,
dot matrix and line printers).
Non-impact printers have no mechanical contact between paper and printing head (e.g. ink-jet,
desk- jet, laser printers).
Assignment: State the advantages and disadvantages of impact and non-impact printers?
1.3.3. Registers
Registers are special storage locations within the CPU that offer an advantage of speed. They work
under the direction of the control unit to accept and hold data that is being processed. Since the CPU
uses registers for the processing of data, the number of registers in a CPU and the size of each
register affect the power and speed of the CPU.
26
Advanced Level Computer Science/ICT
Registers are grouped into two: special purpose registers and general purpose registers.
General purpose registers on the other hand have no specific function; they are used according
to the need of the program being executed.
Answer: Processing is performing arithmetic operations (add, subtract, multiply, divide etc) or logical
operations (comparisons like less than, greater than, equal to etc) on data to convert it to useful
information.
Steps 1 and 2 together are called instruction time or I-time and steps 3 and 4 together are called
execution time or E-time. The combination of I-time and E-time is called the machine or instruction
27
Advanced Level Computer Science/ICT
cycle or the fetch-decode-execute cycle. The length of time taken to fetch, decode and execute an
instruction is measured in clock cycles.
Computer storage can be classified basically into two: primary storage and secondary storage.
Dynamic RAM (DRAM) consists of capacitors that slowly leak their charge over time. Thus, they
must be refreshed every few milliseconds to prevent data loss. DRAM is cheap memory owing
to its simple design.
28
Advanced Level Computer Science/ICT
Static RAM (SRAM) consists of circuits that retain their charge over time. SRAM is faster and
more expensive than dynamic RAM, and does not need to be refreshed as DRAM does. Due to its
cost it is not used as main memory but rather to build cache memory.
Masked ROM isROM programmed with its data when the chip is fabricated.
Programmable ROM(PROM) isROM that can be programmed once but not reprogrammed.
Erasable Programmable ROM (EPROM) is ROM that can be erased by strong ultraviolet light
and new data burnt into it. To do this the chip has to be removed from the machine and put
back after the changes have been made.
Electrically Erasable Programmable ROM (EEPROM) isROM whose content can be erased
electrically. In this case, the chip need not be removed from the machine. The programming is
done using special software.
c. Cache Memory
Cache memory is a smaller and faster memory between the CPU and main memory, which stores
copies of data from the most frequently accessed memory locations. The purpose of cache memory
is to speed up accesses by storing recently used data closer to the CPU, instead of storing it in main
memory. Cache is static RAM and is usually organized in levels:
Level 1 (L1) cache, Level 2 and Level 3 cache.
Level 1 cache is closest to the CPU or within it.
L2 and L3 caches are outside it.
When the CPU needs to access memory, cache memory is examined first. If the data is found in cache,
it is read from it. Otherwise, main memory is accessed. When the CPU refers to memory and finds
the data in cache, it is said to be a HIT. Otherwise, it is a MISS.
a. Magnetic Storage
29
Advanced Level Computer Science/ICT
Magnetic storage devices store data as electromagnetic charges on the magnetic surfaces of the
storage units. Examples are floppy disks, hard disks and magnetic tape.
Floppy Disk
A floppy disk consists of a round flexible plastic disk coated with a magnetic substance and
protected by a plastic cover lined with a soft material that wipes the disk clean as it spins. The disk
is made of two recordable surfaces which are divided into a number of circular paths called tracks.
The number of tracks per surface varies with the particular type of disk. Each track is in turn
divided into a number of smaller units called sectors. A sector is the basic unit of storage on the disk
and has a capacity of 512 bytes.
Floppy disk
Hard Disk
A hard disk consists of several metallic platters which store data. Each platter has two sides and is
divided into a number of rings called tracks. Tracks on a platter are numbered 0 from the outside
and usually go up to 1023. Each track is divided into sectors. A sector is the basic unit of storage on
the disk and has a capacity of 512 bytes. Sectors are grouped together to form clusters. A cluster is
the smallest logical amount of disk space that can be allocated to hold a file. A cylinder is a sum set
of all the tracks on all the platters that have the same track value.
Factors that determine the performance of hard disks are, seek time and drive rotational speed.
o Seek time is the time taken to move the read/write head over the right track and sector.
o Drive rotational speed is the total number of revolutions the disk platters make per minute.
Higher rotational speed leads to higher transfer rate.
Hard disk
Magnetic Tape
A magnetic tape consists of a magnetically coated stripe on which data is stored. Data is stored on
the magnetic tape in chronological order or sequentially. This means that any piece of data is always
stored in the next available space on the tape. To access data, the tape drive has to move through all
30
Advanced Level Computer Science/ICT
the preceding data before it can access the desired data. This mode of access is known as sequential
access. Less susceptible to environment, they are suitable for long-term storage and backup.
b. Optical Storage
Optical storage devices store data as microscopic light and dark spots on the disk surface. Examples
are Compact discs, digital versatile discs and Blu-ray discs. They are less susceptible to
environmental damage.
Compact disc
31
Advanced Level Computer Science/ICT
a. Capacity
The capacity of a storage device is the maximum amount of data that can be stored on the device’s
medium.It is expressed in terms of the number of data bytes the device can hold. This simply means
the unit of measurement of storage capacity is byte. Units of storage are summarized as follows:
1 bit = 0 or 1
4 bits = 1 nibble
8 bits = 1 byte 1 character
1024 bytes = 1 kilobyte (KB) approx. 1/2 page
1024 KB = 1 megabyte (MB) approx. 500,000 pages
1024 MB = 1 gigabyte (GB) approx. 5 million pages
1024 GB = 1 terabyte (TB) approx. 5 billion pages
b. Access time
32
Advanced Level Computer Science/ICT
Access time is the average time taken for a storage device to search and read required data on its
medium. In other words, it is how fast data can be read from or written to a memory device’s
medium. It is measured in seconds. Units of time are summarized as follows:
Millisecond (ms) =
Microsecond (µs) =
Nanosecond (ns) =
Picoseconds (ps) =
Femtoseconds (fs) =
c. Access Method
An access method is the technique used to retrieve information from or store information to a
medium. Storage media can be accessed in two ways: sequentially or randomly.
Sequential Access
The medium is accessed by proceeding from the beginning of the medium until the designated area
is reached. Any new data is stored in the next available space on the medium. To read any data
stored on the medium, the device has to start from the beginning going through each data until the
required data is found. An example of sequential access medium is magnetic tape.
Random Access
Data is accessed in any order, regardless of its location on the medium. To read any data stored on
the medium, the device does not need to go through all preceding data. It is also called direct access.
Examples of direct access devices are RAM, ROM, CDs, DVDs and magnetic disks.
d. Volatility
Volatility refers to the behavior of the device without power. A device can be volatile or non-
volatile.Volatile means that the device loses its content when power is switched off. Examples of
volatile devices are Cache and RAM.
Non-volatile means that the device preserves its content even without power. Examples of non-
volatile devices are ROM, magnetic disks, optical discs and solid state devices.
Registers
Cache Memory
The Motherboard
34
Advanced Level Computer Science/ICT
The data bus carries data between the CPU and main memory or peripherals. During a write
operation, data is carried from the CPU and during a read operation, data is carried into the CPU.
This means that the data bus is bidirectional. The size of the data us determines how much data can
be transferred in a single operation.
When the CPU wants to read data from a memory location, it sends out the memory address of the
desired data on the address bus and then sends out a Memory Read signal on the control bus. The
memory read signal enables the addressed memory device to output the data onto the data bus. The
data from the memory travels along the data bus to the CPU.
a. I/O Ports
A port isa pathway for data and information to go into and out of the computer from external
devices such as keyboards, monitors and printers.
There are many standard ports as well as custom electronic ports designed for special purposes.
Examples of ports are:
o PS/2 ports for connecting the keyboard and mouse
o VGA (Video Graphics Adapter) port for connecting the monitor
o RJ45 port for connection to an Ethernet network
o RJ14 for connection to the Internet via phone line
o USB port for connecting USB devices like Flash drives, printers, keyboards and mice
o Serial ports for connecting serial devices like PDAs
o Parallel port connecting parallel devices like printers
35
Advanced Level Computer Science/ICT
o Firewire is high performance serial bus, for connecting devices to your personal computer.
FireWire provides a single plug-and-socket connection on which up to 63 devices can be
attached with data transfer speeds up to 400 mbps.
SISD Architecture
36
Advanced Level Computer Science/ICT
PE 1 DS 1
Control Unit PE 2 DS 2
IS
DS = Data Stream
DSn IS =Instruction Stream
PE n PE = Processor Element
Instruction
stream
Memory
SIMD Architecture
�� 2
Control Unit 2 PE 2
�� �
Control Unit n PE�
MISD Architecture
37
Advanced Level Computer Science/ICT
IS 2 DS 2
Control Unit 2 PE 2 DS = Data Stream
IS = Instruction Stream
IS � DS n
ControlUnit� PE n
Memory
MIMD Architecture
Assignment: SIMD, MISD and MIMD machines are known as parallel processing machines.
What do you understand by parallel processing?
Answer: Parallel processing is the use of multiple (independent) processors simultaneously to execute
a single program or task.
Parallel processing divides a single problem into portions so that multiple processors work on their
assigned portion of the problem at the same time. Parallel processing requires special software that
recognizes how to divide the problem and then bring the results back together again.
Some personal computers implement parallel processing with dual-core processors or multi-core
processors. Others have two or more separate processors. Others have two or more separate processor
chips, respectively called dual processor chips, respectively called dual processor or multiprocessor
computers.
3. Processor Architecture
A processor’s architecture refers to the way in which its memory and control are organized.
38
Advanced Level Computer Science/ICT
Definition: An instruction set is the collection of bit patterns or binary codes for the machine
operations that a processor has been designed to perform.
An instruction set architecture (ISA) is the interface between the computer's software and
hardware and also can be viewed as the programmer's view of the machine. Besides instructions, it
defines items in the computer that are available to a program - e.g. data types, registers, addressing
modes, and memory.
There are two types of fundamental CPU architectures based on the notion of instruction set:
complex instruction set computers and reduced instruction set computers.
Examples of CISC processors are: Intel 386, 486, Pentium, Pentium Pro, Pentium II, Pentium III,
Motorola’s 68000, 68020, 68040, etc.
39
Advanced Level Computer Science/ICT
For example, ADD A, #0E – ADD is the op-code; A and #0E are operands
MOV AX, 0 – MOV is the op-code; AX and 0 are operands
Operands can be specified in different ways in an instruction. The way an operand is specified in an
instruction is known as an addressing mode.
Definition: An addressing mode refers to the way in which the processor locates the data (operand)
associated with an instruction.
There are dozens of possible addressing modes, but they all generally fall into one of the following
categories: direct addressing, indirect addressing and indexed addressing.
a. Direct Addressing
b. Indirect Addressing
c. Indexed Addressing
4. Software
40
Advanced Level Computer Science/ICT
BIOS for hardware that changes occasionally. It requires extra volatile information so it is
stored on a separate chip called CMOS (Complementary Metal Oxide Semiconductor).
41
Advanced Level Computer Science/ICT
b. Spreadsheet software
Examples are MS Excel, Lotus 1-2-3, Quattro Pro, Apple Numbers
c. Database Software
Examples are MS-Access, Oracle, Dbase, FileMaker Pro
d. Presentation Software
Examples are MS PowerPoint, HyperStudio, Digital Chisel
e. Desktop Publishing Software
Examples are MS Publisher, Adobe PageMaker, Quark Express
An integrated software package is software that consists of multiple applications bundled together.
They usually have related functions, features and user interfaces, and may be able to interact with
each other. Examples are Microsoft Office, OpenOffice, Lotus Smart suite and Microsoft works.
42
Advanced Level Computer Science/ICT
also called bespoke software or tailor made software as it is tailored to the exact requirements of
the user or organization.
4.3.2. Shareware
Shareware is copyrighted software that allows you to use it for a trial period but you must pay a
registration fee to the owner for permanent use. Purchasing the right to use the software may also
get you a version with more powerful features and published documentation.
4.3.3. Freeware
Freeware is copyrighted software that is licensed to be copied and distributed without charge.
Freeware is free but it is still under the owner’s control. Examples are Eudora and Netscape.
IV. SOFTWARE
Introduction
A computer system is basically made up of hardware and software. Hardware refers to the physical
components of the computer. They are the parts of the computer that can actually be seen and
touched like the keyboard, mouse, monitor and internal circuits.Software on the other hand, refers
to the collection of computer programs and data that run on a computer, and which make the
hardware useful. They are the intangible components of the computer system.
Computer software has two major categories namely system software and application software.
1. System Software
System software control and coordinate computer resources (hardware and operations) so that the
computer user and applications can smoothly interact. They help the computer carry out its basic
43
Advanced Level Computer Science/ICT
operating tasks. System software are designed to perform computer related tasks. They include
operating systems, firmware, utility programs, device drivers, library programs and language
translators.
OS structure
a. OS Kernel
The kernel is the central part of an operating system that is running at all times on the computer. It
loads first and remains in memory as long as the computer is on. It consists of utilities (file manager,
memory manager, device drivers, process manager etc.) that perform basic required functions. In
many operating systems, only the kernel can access hardware directly.
b. Command Interpreter
The command interpreter (processor) is the part of the operating system that understands and
executes commands that are entered interactively by a human being or from a program.In some
operating systems the command interpreter is called shell.It provides an interface between users
and the operating system (kernel).When a user logs in, a shell is started up.
44
Advanced Level Computer Science/ICT
c. SystemCalls
The interface between the OS and the user program is defined by a set of instructions called system
calls. User programs use system calls to talk with the operating system.
Definition: System call is the mechanism by which a program requests a service from the operating
system’s kernel.
When a running program needs a service from the operating system, it calls a system call.
a. Segmentation
Segmentation is when memory is divided into variable sized units called segments. When segments
are used, memory allocation can be done in three different ways:
o First fit allocates the first free segment that is large enough for the new process.
o Best fit allocates the smallest block among those that are large enough for the new process.
o Worst fit allocates the largest block among those that are large enough for the new process.
b. Paging
Paging is when memory is divided into fixed-size units called frames. Jobs are broken up into blocks
of same size as frames called pages which are allocated a number of frames. The OS then uses a page
table to map program pages to memory frames. The pages for each job could be in logical order or
they may be scattered about wherever there is a free frame.
c. Virtual Memory
A program may require more memory than it is available. To solve this problem, virtual memory is
used. Virtual memory is part of the hard disk that is used as an extension of RAM. It is slower, but it
is considerably bigger. As execution goes on, data is being swapped between RAM and virtual
memory.
When a program is running, only the pages that contain the necessary data are kept in RAM while
those that are not needed are kept on disk. For example, a program that has been minimized for a
long time may be transferred to virtual memory so as not to fill up the main memory.
Disk thrashing occurs when the OS has to spend a considerable proportion of its time swapping data
between virtual and real memory.
45
Advanced Level Computer Science/ICT
Process states
Definition: The turnaround time for a process is the amount of time between the time the process
arrives the ready state and the time it exits the running state for the last time.
In other words, it is the length of time it takes to run a process from initialization to termination,
including all the waiting time.
Answer:
i) Scheduler: the part of the kernel in charge with the strategy for allocation/de-allocation of the
CPU to each competing process. It maintains a record of all processes(called process table) in
the OS, adds new processes to the process table and removes the ones that are completed.
ii) Dispatcher: the component of the kernel that oversees the execution of the scheduled processes.
It performs “process switch” – procedure to change from one process to another.
The operating system manages a large amount of data about a process like the program counter
(PC), CPU registers, memory management information, I/O status, scheduling data and process state.
This data is stored in a data structure called a process control block (PCB) also called process
46
Advanced Level Computer Science/ICT
descriptor or state vector. Every process has its PCB and each time a process is moved to the
running state, its register values are loaded into the CPU while register values for the currently
running process are stored into its PCB. This exchange of information is called a context switch.
a. Process Synchronization
In a multi-tasking system, processes compete for resources. A resource is anything that is required
by a process to accomplish its task (processor, memory, I/O device, bus, file etc). Some resources
can only be used in a non-sharable or exclusive mode. That is, they cannot be used by more than one
process at a time. Such resources are known as critical resources. A critical section is a part of a
program where it has access to a non-sharable (critical) resource. To prevent two or more
processes from entering their critical sections over the same resource, processes must be
synchronized.
Definition: Process synchronization is about getting processes to coordinate together in order to avoid
two or more processes entering into critical section over the same resource.
b. Deadlock
Deadlock is a permanent blocking of a set of processes competing for resources. It is asituation in
which each of two processes is waiting for the other to do something; thus, neither one can proceed.
For a deadlock to occur, the following four conditions must hold.
Mutual Exclusion: At least one resource must be held in a non-sharable way.
Hold and Wait: A process must be holding a resource and waiting for another.
No Preemption: No resource can be forcibly removed from a process holding it.
Circular Wait: A waits for B, B waits for C, C waits for A.
Deadlock can be prevented by ensuring that one of the above conditions does not hold. For example
using pre-emptive scheduling.
c. Starvation
Starvation is a situation where a task can never finish because it can never get a necessary resource
such as a large block of memory. The operating system should detect such tasks and do its best to
allocate the resources that they need.
47
Advanced Level Computer Science/ICT
Preemptive scheduling is scheduling in which the currently executing process is forced to give
up the CPU. Scheduling under (2) and (3) is preemptive.
Non preemptive scheduling is scheduling in which the currently executing process gives up the
CPU voluntarily. Scheduling under (1) and (4) is non-preemptive.
There exist different algorithms used for scheduling. Examples are first come, first served, shortest
job first and round robin algorithms.
P1 140
P2 75
P3
P4 280
P5 125
Disadvantage
48
Advanced Level Computer Science/ICT
Some jobs may never be executed as they have a high service time (starvation).
c. Round Robin
Round-robin algorithm distributes time equitably among all ready processes by establishing a
particular time slice (or time quantum), during which each process executes. At the end of the
quantum, the process is preempted. It returns to the ready state to allow another process its turn.
Using round-robin algorithm with time slice of 50, the above processes will be scheduled as follows:
a. Interrupts
An interrupt is a signal generated by hardware or software that causes the CPU to suspend what it is
doing to handle another task of higher priority. Any event that will cause an interrupt is called an
interrupt request (IR). For example, a key pressed on the keyboard. An interrupt handler or
interrupt service routine (ISR) is a program that services an interrupt request. It contains the
actions that will be executed for a given interrupt request.
b. Polling
c. Buffering
A buffer is an area of memory used to temporarily store data while it is being moved from one place
to another.
49
Advanced Level Computer Science/ICT
50
Advanced Level Computer Science/ICT
2.2. MultiUser OS
A multi-user operating system is an operating system which allows multiple users to work on the
system simultaneously. This type of operating system is larger and more complex than a single user
operating system.
Features of multi-user operating systems, which are not provided in single user operating systems,
are:
o Time sharing (CPU devotes time to all the users in round robin fashion).
o Tight security features.
o Resource sharing among users.
o System administrator privileges
Examples of multi-user operating systems are Linux, Unix and Virtual Machine System (VMS).
2.4. MultiprogrammingOS
A multi-programming operating system is an operating system that allows multiple programs to be
held in main memory at the same time. The concept of multi-programming is that the operating
system keeps several jobs in memory simultaneously and decides which can be executed at a given
moment.
2.5. MultitaskingOS
A multitasking operating system allows a user to execute more than one program at a time. It allows
a user to be preparing a worksheet on the computer while printing a report or listening to music.
Multitasking is an extension of multiprogramming as two programs cannot be executed
simultaneously if they are not found in memory at the same time.
Windows Me, Windows-XP, Macintosh operating system, OS/2 are examples of single user,
multitasking operating systems.
51
Advanced Level Computer Science/ICT
2.6. Embedded OS
An embedded operating system is an operating system that is used in an embedded system. An
embedded system is a small computing device that is built into a larger equipment often as a single
chip and dedicated to a given task. Embedded systems control many devices in use today such as
digital watches, mobile phones, microwave ovens, washing machines, vehicles, photocopiers,
cameras and process controllers.
Embedded OS are ROM based. That is, they cannot be modified as ROM is read only.
2.7. Network OS
A network operating system is an operating system which includes networking features. It contains
special functions, protocols and device drivers that enable the computer to be connected to a
network.
Examples of network operating systems are Windows-NT, Windows-2000 server, Windows server
3000, Novell Netware and Artisoft LANstatic.
Some multi-purpose operating systems like Windows XP, Windows 7 and Mac OS 10, come with
capabilities that enable them to be described as network operating systems.
Introduction
Computers process and store all forms of data in binary format.
1. Data Hierarchy
Data items processed by computers form a data hierarchy in which they become larger and more
complex in structure as we progress from bits, to characters, to fields and to larger data elements.
Data elements can be organized in a hierarchical form as follows:
Bit
The smallest data item manipulated by computers is the bit (short for binary digit). Each bit can
assume either the value 0 or the value 1.
Byte
A single bit is of little or no use as it can represent only two states. To make them important, they
are usually used in groups. A group of eight bits is known as a byte. A byte is the smallest
addressable unit of the computer and it is used to represent a character. Each character, be it a
letter, a digit or a symbol is represented as an eight bits pattern. The word “data” has 4 characters,
meaning that it will take up 4 bytes which is 32 bits.
Field
52
Advanced Level Computer Science/ICT
As characters are composed of bits, fields are composed of characters. A field is a group of
characters that conveys some meaning. For example, a person’s name, a word, the name of a place
or thing.
Record
A record is a collection of related fields. A record consists of fields, with each field describing an
attribute of an entity.
File
A file is a collection of related records. Files are frequently classified by the application for which
they are primarily used. A primary key in a file is a field whose value identifies a record among
others in the file.
Databases
A database is a collection of files.
2. File Formats
Records in a file must be stored in a way that a program that uses the file will be able to recognize
and possibly access it. This is known as file format.
Definition: File format is a particular way that data is encoded for storage in a computer file.
A particular file format is often indicated as part of a file's name by a file name extension.
Conventionally, the extension is separated from the file name by a dot and contains three or four
letters that indicate the format. A file name is a unique name that is given to a file within its file
directory. For example, lectures.docx is a file with filename “lectures” and extension “.docx”
indicating that the file is an MS Word 2007 document.
There are as many different file formats as there are different programs to process the files. A few of
the more common file format types are:
53
Advanced Level Computer Science/ICT
54
Advanced Level Computer Science/ICT
o MIDI-
3. File Organization
File organization refers to the logical structuring of records in a file. In other words, it is the way
records are arranged in a file.
In the context of data processing, files can be grouped into two types: master and transaction files.
A master file contains the permanent data of a data processing system. Master files represent
the most up to date situation of the system and contain two basic types of data:
o data of a more or less permanent nature which only requires updating occasionally;
o data which will change every time transactions are applied to a file.
A transaction filecontains data that is necessary to keep a master file up to date. Data iscollected
on a daily, weekly or monthly basis into a transaction file which is then used toupdate the
master file.
Depending on the arrangement of records in a file, files can be serially, sequentially or randomly
organized.
55
Advanced Level Computer Science/ICT
4. Processing Files
The main processes that can be performed on files are adding records, deleting records and
updating records.
56
Advanced Level Computer Science/ICT
File B now contains the amended data and file A still exists with the original data.
57
Advanced Level Computer Science/ICT
Endif
Endwhile
Close file A
Close file B
58
Advanced Level Computer Science/ICT
4.4.1. Atomicity
Atomicity requires that database modifications must follow an “all or nothing” rule. This means
that,if one part of a transaction fails, the entire transaction fails and the database state is left
unchanged. This guarantees that a transaction cannot be left in an incomplete state.
4.4.2. Consistency
Consistency ensures that any transaction will bring the database from one valid state to another.
Any data written to the database must be valid according to all defined rules.
4.4.3. Isolation
Isolation refers to the requirement that no transaction should be able to interfere with another
transaction. No transactions that affect the same rows can run concurrently since their sequence
and hence their outcome would be unpredictable.
4.4.4. Durability
Durability means that once a transaction has been committed, it will remain so even in the event of
power loss, crashes or errors.
1. Number Systems
A number system is a set of symbols and rules used to represent numbers. The number of different
symbols used in a given number system is known as the base or radix of the system. The largest
value of a symbol (digit) in a given number system is always one less than the base or radix of that
system. If the base of a system is represented by“�”, then the largest value a digit in that system can
assume is “� − 1”.
59
Advanced Level Computer Science/ICT
Examples of number systems include the binary, octal, decimal (denary) and hexadecimal systems.
The value of any digit in a given n-digit number is obtained by multiplying the digit by its place value.
The value of the number is the sum of the products of the digits and their place values. That is, we
multiply each digit by its place value, then we add the different products obtained.
Example: 23410 = 2 × 102 + 3 × 101 + 4 × 100 . This means that there are two one hundreds, three
tens and four ones in the number 234.
Remark Each digit position in decimal has a weight that is ten times the one to its immediate right.
That is, 102 is ten times greater than 101 which is ten times greater than 100 .
60
Advanced Level Computer Science/ICT
Octal positions
61
Advanced Level Computer Science/ICT
Example: 3678 = 3 × 82 + 6 × 81 + 7 × 80
(This means that there are 3 sixty fours, 6 eight’s and 7 one’s in 367)
16 + 8 + 2 = 2610
b. Binary to Decimal
There are two methods that can be used to convert decimal numbers to binary:
- repeated division method
- repeated subtraction method
62
Advanced Level Computer Science/ICT
The general technique of this method can be used to convert any decimal number to any other
number system.
Step 1: divide the decimal number you want to convert by 2 in regular long division until you
obtain a final remainder
Step 2: use the remainder as the least significant bit of the binary number
Step 3: divide the quotient you got from the first division operation by 2 until you obtain a final
remainder
Step 4: use the remainder as the next digit of the binary number
Step 5: repeat steps 3 and 4 as many times as necessary until you get a quotient that cannot be
divided by 2.
Step 6: use the last remainder (that cannot be divided by 2) as the most significant bit of the
binary number.
63
Advanced Level Computer Science/ICT
2510 = 110012 ,
0.75 × 2 = 1.5 1
0.5 × 2 = 1.0 1
0.7510 = 112
⇒ 25.7510 = 11001.112
Theorem
If base R1 is the integer power of another base, R2(i.e. R1 = R2d),then every group of d digits in R2 is
equivalent to 1 digit in the R1 base.
For example:
Assume that: R1 = 8 (octal) and R2 = 2 (binary)
64
Advanced Level Computer Science/ICT
a. Binary to Octal
Step1: make groups of three bits starting from the least significant bit and move towards the most
significant bit.
Step 2: replace each group of bits by its octal representation.
011 3
Example1: Convert 738 to binary
100 4
78 = 1112 , 38 = 1012
101 5
∴ 738 = 1111012
110 6
111 7
Example 2: Convert 4508 to binary
48 = 1002 , 58 = 1012 , 08 = 0002
65
Advanced Level Computer Science/ICT
∴ 4508 = 1001010002
0000 0 1000 8
0001 1 1001 9
0010 2 1010 A
0011 3 1011 B
0100 4 1100 C
0101 5 1101 D
0110 6 1110 E
0111 7 1111 F
a. Binary to Hexadecimal
Step1: make groups of four bits starting from the least significant bit and move towards the most
significant bit.
Step 2: replace each group of bits by its hexadecimal value representation.
∴ 1001102 = 2616
∴ 10111012 = 5�16
b. Hexadecimal to Binary
66
Advanced Level Computer Science/ICT
To convert from hexadecimal to binary, we carry out the inverse operation. That is, we replace
every hexadecimal digit by its 4-bits binary equivalent.
Assignment:
1) Convert the following octal numbers to hexadecimal.
i) 658
ii) 538
2. Data Representation
Computers use binary patterns (fixed number of bits) to represent data, which could be numbers,
letters, videos, images or other symbols. It is important to decide on how these patterns will be
interpreted. The interpretation of binary patterns is called data representation or encoding.
Different representation schemes exist.
For example:
o A 4-bit pattern will represent the integers 0 to 24 − 1 = 3
o An 8-bit pattern will represent the integers 0 to 28 − 1 = 255
67
Advanced Level Computer Science/ICT
Example 1: Using 1’s complement, represent the following base 10 numbers on 8 bits.
i) 2610 = 11010
Number is positive ⇒ sign bit is 0
⇒2610 = 0 0011010
ii) −25
Number is negative ⇒ sign bit is 1
25 = 11001
Complement of 0011001 is 1100110
68
Advanced Level Computer Science/ICT
⇒−25 = 1 1100110
Example 2: Give the decimal equivalent of the following 1’s complement binary representations.
i) 0010 0001.
Sign bit is 0 ⇒ positive
Absolute value is 010 0001 = 33
Hence, the integer is +33
The problem with this representation is that there are still two representations for zero (0000 0000
and 1111 1111).
69
Advanced Level Computer Science/ICT
o for negative integers, the absolute value of the integer is equal to "the magnitude of the
complement of the (� − 1)-bit pattern plus one". That is, we just add one to 1’s complement
to get 2’s complement.
ii) −13
Number is negative ⇒ sign bit is 1
13 = 1101 = 0001101
1’s complement of 13 is 1110010
2’s complement of 13 is 1110010 + 1 = 1110011
⇒− 13is represented by 1 1110011
Example 2: Give the decimal equivalent of the following 2’s complement binary representations.
i) 01100000
Sign bit is 0⇒ positive
Absolute value is 110 0000 = 96
Hence, the integer is +96
Modern computers use 2's complement in representing signed integers. This is because:
2. There is only one representation for the number zero unlike in sign-magnitude and 1's
complement representations.
3. Positive and negative integers can be treated together in addition and subtraction.
Subtraction can be carried out using the "addition logic".
70
Advanced Level Computer Science/ICT
71
Advanced Level Computer Science/ICT
the most significant bit is the sign bit (S), with 0 for negative numbers and 1 for positive
numbers.
the following 16 bits represent the exponent (E).
the remaining 47 bits represent the mantissa (M) or fraction (F).
In floating-point representation, the mantissa and exponent play two important roles. The mantissa
affects the precision of the number while the exponent affects the range. Precision has to do with
the exactness of a number while range has to do with the set of numbers that can be represented.
For simplicity, we will use a 14-bit pattern for floating point with a 5-bit exponent and an 8-bit
mantissa. In this case, we will use excess-16 representation for the exponent.
Examples:
1. Represent the following numbers as 32-bit single precision floating-point numbers.
a. 32.2
b. −15.37
c. 0.125
Solution:
a. We convert the number to binary
32 = 100000
0.2 = 0.2 × 2 = 0.4 0 ���
= 0.4 × 2 = 0.8 0
= 0.8 × 2 = 1.6 1
= 0.6 × 2 = 1.2 1
= 0.2 × 2 = 0.4 0
= 0.4 × 2 = 0.8 0
= 0.8 × 2 = 1.6 1
= 0.6 × 2 = 1.2 1
Step 4: The mantissa stored is what is on the right side of the radix point of the normal form.
72
Advanced Level Computer Science/ICT
So M is 0000000110011001100110
0 10101 00000001[10011001100110]
NB: On 8 bits we see that part of the number will be missing. That is why we say the mantissa
determines the precision (exactness) of the number.
b. −15.375
Negative number ⇒ sign bit is 1
15 = 1111
0.375 × 2 = 0.75 0 ���
0.75 × 2 = 1.5 1
0.5 × 2 = 0.96 0
0.5 × 2 = 1.0 1
0.375 = 0101
15.375 = 1111.0101
Normalized we have, 1.1110101 × 23
� = 3 ⇒ 19in excess-16
� = 10010
−15.375is represented as 1 10010 11101010
c. 0.125
Positive number ⇒Sign bit is 0
0 = 0000
0.125 × 2 = 0.25 0 ���
0.25 × 2 = 0.5 0
0.5 × 2 = 1.0 1
0.125 = 0.001
Normalized we have, 1.0 × 2−3
� =− 3 + 16 = 13 = 01101
2. Suppose the following 14-bit floating-point representation patterns, what decimal numbers do
they represent?
a. 01000011000000
73
Advanced Level Computer Science/ICT
b. 10111010000000
c. 11111000000001
Solutions:
a. 010000110 00000
Sign bit is � = 0 ⇒positive number
� = 10000 = 16 (in normalized form)
Fraction is 1.11 (with an implicit leading 1) = 1 + 1 × 2−1 + 1 × 2−2 = 1.75
The number is +1.75 × 2(16−16) =+ 1.75 × 20 = + 1.75
b. 10111010000000
Sign bit � = 1 ⇒ negative number
� = 01110 = 13 (in normalized form)
Fraction is 1.1 (with an implicit leading 1) = 1 + 1 × 2−1 = 1.5
The number is −1.5 × 2 13−16 =− 1.5 × 2−3 = − 1.625
c. 1 11110 00000001
Sign bit � = 1 ⇒ negative number
� = 11110 = 30 (in normalized form)
Fraction is 1.00000001 (with an implicit leading 1) = 1 + 2−8
The number is −(1 + 2−8 ) × 2(30−16)
74
Advanced Level Computer Science/ICT
Introduction
1. Boolean Algebra
Boolean algebra also known as the algebra of logic was developed by an English mathematician
called George Boole. It deals with binary variables and logic operators operating on these variables.
A binary variable has only two possible values 0 or 1. Logic operators operating on these variables
are AND (·), OR (+) and NOT (‘). Operations are defined for the values 0 and 1 as follows:
AND
OR
0·0 = 0 NOT
0+0 = 0
0·1 = 0 0=1
0+1 = 1
1·0 = 0 1=1
1+0 = 1
1·1 = 1
1+1 = 1
o Associative law
(�·�)·� = �·(�·�)|(� + �) + � = � + (� + �)
o Distributive law
�(� + �) = (��) + (��) | � + (��) = (� + �)(� + �)
o Identity law
�·1 = � | � + 0 = �
o Redundancy law
�·0 = 0 | � + 1 = 1
o Complement law
�∙�=0 | �+�=1
o Idempotence law
�·� = � | � + � = �
75
Advanced Level Computer Science/ICT
o Absorption law
� � + � = � | � + �� = �
o Involution law
�=�
o No name
� + �� = � + � | � � + � = ��
�� + �� = � | (� + �)(� + �) = �
o De Morgan’s Theorems
�� = � + � | � + � = � ∙ �
76
Advanced Level Computer Science/ICT
i) � + �� = �
ii) (� + �) = �(� + �)
iii) (� + �)(� + �) = �
77
Advanced Level Computer Science/ICT
a. AND Gate
It is a logic gate whose output is “true” only when both inputs are “true”. If neither or only one of the
inputs is “false”, the output is “false”. The following illustration and table show the circuit symbol
and logic combinations for an AND gate.
A B Output
Logic AND 0 0 0
0 1 0
1 0 0
1 1 1
b. OR Gate
It is a logic gate whose output is “true” when either or both of the inputs are “true”. If both inputs
are "false," then the output is "false."
Logic OR
A B Output
0 0 0
0 1 1
1 0 1
1 1 1
c. NOT Gate
It is a logic gate whose output is “false” if its input is “true” and vice versa. It is called logical inverter,
because it reverses the state of its input. A NOT gate accepts one input and produces a single output.
A Output
0 1
1 0
Logic NOT (inverter)
78
A B Output
Advanced Level Computer Science/ICT
0 0 1
0 1 1
1 0 1
1 1 0
d. NAND Gate
The NAND gate operates as an AND gate followed by a NOT gate. The output is "false" if both inputs
are "true." Otherwise, the output is "true.
Logic NAND
e. NOR Gate
A NOR gate is equivalent to an OR gate followed by a NOT gate. Its output is "true" if both inputs are
"false." Otherwise, the output is "false."
A B Output
0 0 1
0 1 0
1 0 0
Logic NOR 1 1 0
f. XOR Gate
Exclusive-OR is a logic gate whose output is “true” when one but not both of its inputs is “true”. The
output is "false" if both inputs are "false" or if both inputs are "true." Another way of looking at this
circuit is to observe that the output is “true” if the inputs are different, but “false” if the inputs are
the same.
A B Output
0 0 0
Logic XOR 0 1 1
1 0 1
1 1 0
79
Advanced Level Computer Science/ICT
Exercise 2: What are the outputs for the following logic circuits
Introduction
A system is an integrated set of regularly interacting or interdependent components created to
accomplish a defined objective, with defined and maintained relationships among its components.
Basically, there are three major units in every system namely input, processing and output. The
objective of a system demands that some output be produced as a result of processing the suitable
inputs.
An information system can therefore be seen as a set of interrelated components that collectdata,
process the data to produce information.
80
Advanced Level Computer Science/ICT
For example, the number 12.5 is data because we do not know why or in what context it is being
used. However, if the number appears on a student’s report card to show that they have an average
of 12.5, then this data has changed into information, because it has acquired a context (it’s an
average) and meaning.
Also, the binary patterns that describe an icon on your desktop are data. They become information
after the operating system software has processed them, because then they become meaningful to
you as the icons representative of your hard disk or Internet explorer.
In summary,
����������� = ���� + �������
b. Interview
An interview is a meeting during which somebody is asked questions. Interviews allow you to
collect a greater depth of data and understanding from people than is possible by just using a
questionnaire.
c. Observation
In observation, the data gatherer observes what is happening during a process or event and
produces some kind of data file as a result
d. Data logging
Data logging is an automated method of gathering data by using sensors.
e. Document review
Document review is getting relevant data from a document, an article or a book.
f. Data mining
Data mining is the exploration of databases to collect data.
a. Timeliness
Delay destroys the value of information. For effective decision making, information must reach the
decision-maker at the right time. Timeliness means that information must reach its recipients
within the prescribed timeframes.
81
Advanced Level Computer Science/ICT
b. Accuracy
Wrong information given to decision-makers would result in wrong decisions. Accuracy means that
information should be free from mistakes and errors.
c. Current
For the characteristic of timeliness to be effective, information should be current or up-to-date.
Information must be current as a fact of yesterday may not be a fact of today.
d. Completeness
Information should have every necessary part or everything that is wanted. If information is not
complete, it may lead to wrong decisions being made as only half of an entirety of the information is
known.
e. Explicitness
Good information should not require further analysis for decision making. It should be clear and
obvious, leaving no doubts as to its intended meaning.
a. Data Verification
Verification means checking the input data to make sure it has been entered correctly. Verification
tries to ensure there have been no transcription errors. It is a check on accuracy.Two methods of
data verification are double entry and proofreading.
Double Entry
Double entry consists of entering the data twice. The two entries are then compared against each
other and a warning given if they do not match. For example, a new password is always entered
twice.
Proof Reading
Proofreading consists of reading the data entered either on screen or printout, to be sure that it
matches the data source. It is also known as visual check.
82
Advanced Level Computer Science/ICT
b. Data Validation
Validation is a check on input data to ensure that the data is sensible or reasonable. It compares the
input with a set of rules that the computer has been told the data must follow. If the data does not
match up with the rules then there must be an error. Validation only checks that the data is valid.
The data may be valid but not correct. Five types of validation checks are:
Type check
A type check is used to ensure that data entered in a field fits the required data type. For example, a
person’s name will consist of letters of the alphabet and sometimes hyphens and apostrophe. Any
name that contains numbers will be rejected as invalid.
Length check
A length check ensures that an entered value is not longer than a certain number of characters. For
example, a phone number has 8 digits. Entering fewer or more digits makes a number invalid.
Range check
A range check is used to ensure that the data entered falls between a specified minimum and
maximum values. For example, a mark in an exam is between 0 and 20. Any mark below 0 or above
20 is rejected as invalid.
Presence check
A presence check ensures that an entry has been made in a particular field. If it has not, the system
will not allow the record to be saved or any entries to be made in later fields. Such fields called
mandatory fields are indicated on some systems by the used of an asterisk.
Check digits
A check digit is a digit attached to the end of a string of digits that can be used to check that the
string is correct. It is calculated from the other digits in the string. One example where a check digit
is used is in the 10 digit ISBN number which uniquely identifies books. The last number of the ISBN
is actually the check digit for the other numbers. For example, in the ISBN 1858134153, the 3 at the
end of the number is the check digit.
The check digit for ISBNs is obtained using a calculation method known as the Modulus-11 weighted
check digit calculation.
Position 10 9 8 7 6 5 4 3 2 1
Digit 1 8 5 8 1 3 4 1 5
Weightings 10 72 40 56 6 15 16 3 10
83
Advanced Level Computer Science/ICT
o Divide the total by 11 and then subtract the remainder from 11. The check digit is the result
of this operation.
228 / 11 = 20 remainder 8 => Check digit is 11-8 = 3.
o Add the check digit to the end of the original number to get the complete product number. i.e.
1858134153.
Position 10 9 8 7 6 5 4 3 2 1
Digit 1 8 5 8 1 3 4 1 5 3
Weightings 10 72 40 56 6 15 16 3 10 3
o Divide the total by 11.If the remainder is 0, then the number has passed the validation check
and so it is likely that it has been inputted correctly.
231 / 11 = 21 remainder 0
Exercise:
i) Dates are read into a computer in the following format: DDMMMYY e.g. 15DEC92. The
following dates were rejected by a validation program: 3JAN71, AUG2166, 31SEP72. State the
validation check used to discover each error.
ii) Calculate the check digitsto complete the ISBNs:019276150-1 and 995640216-8.
iii) Set up a spreadsheet which will calculate and check the validity of Modulo-11 weighted check
digits for any given ISBN.
84
Advanced Level Computer Science/ICT
OMR uses a device called an optical mark reader to read marks made with prescribed pens, pencils
or special writing material on OMR forms, and convert them into information in the computer. This
system is good for multiple choice examination questions.
d. Barcode Reading
An optical device called barcode reader is used to read the barcode on products and convert them
into a form that can be processed by the computer. A bar code is a sequence of vertical lines and
numbers that identify a product. They are used in libraries, supermarkets and retail shops.
e. VoiceRecognition
This method converts speech into text or a sequence of computer commands. It is most common for
data entry and word processing environments.
Hardware
Hardware refers to the physical devices that make up the system. They are the whole set of
equipment used for input, processing, storage and communication of data.
Software
Software is the collection of computer programs used in the system. They provide the instructions
that tell the computer what to do.
Data
Data are raw, unorganized, potentially useful facts and figures that are processed to produce
information.
85
Advanced Level Computer Science/ICT
People
People are the main actors of the system. They are the users of the information system. They input
data into the computer, give some direction to the computer to perform tasks and review
information on the computer for output.
Procedures
Procedures are the series of documented actions taken to achieve a particular goal. A procedure is
more than a single simple task. It can be complex and involved, such as reinstalling software,
performing a backup etc.
Strategic Executives
Level
Tactical Managers
Level
Operational
Workers
Level
At the strategic level, information is needed by senior managers (executives) to help them with
their business plans. Information at this level is used for making long term decisions.
At the tactical level, information is needed by middle managers to help them monitor and
control business activities. Tactical planning and decision-making takes place within the
guidelines set by the strategic plan.
At the operation level, employees with operational roles need information to help them carry
out their duties. Results of operational work are passed upwards to let the tactical planners
evaluate their plans.
In order to meet with the information needs of the organization, different types of information
systems exist which can be groupedinto two: operations support systems and management support
systems.
86
Advanced Level Computer Science/ICT
There are two types of TPS: batch processing and online processing systems.
a. Batch Processing
With batch processing, transaction data is collected over a period of time and all processing is done
as a group. Batch processing is ideal in situations where large amounts of data requiring similar
processing are to be processed. Examples are:
Payrollsystems for calculating employee salaries
Billing systems for calculating consumer bills.
87
Advanced Level Computer Science/ICT
Summary reportsconsolidate data into a format that an individual can review quickly and easily.
To help synopsize information, a summary report typically contains totals, tables, or graphs. An
inventory summary report is an example of a summary report.
Exception reports report information that is outside of a normal condition. These conditions
called the exception criteria, define the range of what is considered normal activity or status.
An example of an exception report is an inventory exception report that notifies the purchasing
department of items it needs to reorder. Exception reports help managers save time because
they do not have to search through a detailed report for exceptions. Instead, an exception
report brings exceptions to the manager’s attention in an easily identifiable form. Exception
reports thus help them focus on situations that require immediate decisions or actions.
88
Advanced Level Computer Science/ICT
o Internal sources of data might include sales, manufacturing, inventory, or financial data from
an organization’s database.
o Data from external sources could include interest rates, population trends, and costs of new
housing construction or raw material pricing.
Examples of DSS are:
Logistics Systems
Financial Planning Systems
Spreadsheet Models
Non-management employees are the primary users of such systems for job-related decisions. For
example, there are expert systems that can diagnose human illnesses, make financial forecasts, and
schedule routes for delivery vehicles.
Expert systems are one part of an exciting branch of computer science called artificial intelligence
(AI). AI is the application of human intelligence to computers. AI technology can sense your actions
and, based on logical assumptions and prior experience, will take the appropriate action to complete
the task. AI has a variety of capabilities, including speech recognition, logical reasoning, and
creative responses.
89
Advanced Level Computer Science/ICT
90
Advanced Level Computer Science/ICT
Introduction
The use of computers and data communications networks has been termed the ‘second industrial
revolution’, because it is revolutionizing the way people work and communicate.
1. Computer Networks
A computer network is a collection of computers and other devices that are connected together so
they can communicate and share resources. The smallest network can be as simple as two
computers linked together. The resources shared include files, folders, printers, disk drives and
anything else that exists on a computer. Any computer or device on a network is called a node.
Networking is the term that describes the processes involved in designing, implementing, upgrading,
managing and otherwise working with networks and network technologies
91
Advanced Level Computer Science/ICT
Internet. The most popular is the Wireless PAN (WPAN), a Bluetooth connection between two
laptop computers or phones.
1.2.3. Hub
A hub is a device that works as central connecting point for multiple computers in a network. It has
ports to which the computers in the network are connected. Data sent to the hub is broadcasted to
all the ports but, only the destination computer receives it. There are three kinds of hubs:
Passive hubs which only split the transmission signal so it can be sent to all the ports
Active hubs (also called Multiport Repeaters) which regenerate data bits to maintain a strong
signal over extended cable lengths
Intelligent hubs (also called Concentrators) usually have their own microprocessor chips and
network operating systems. They can be managed remotely on the network.
1.2.4. Switch
A switch is used at the same place as a hub but the difference between the two is that a switch has a
switching table within it. A switching table stores the Media Access Control (MAC) address of every
computer connected to the switch and sends the data only to the requested address, unlike the hub
92
Advanced Level Computer Science/ICT
which broadcasts the data to all the ports. Switches can therefore be considered as an advanced
form of hubs.
A MAC address is a built-innumber (i.e. set by the manufacturer) consisting of 12 hexadecimal digits
that uniquely and permanently identifies the network adapter of a computer. Examples of a MAC
addressesare 00-14-22-DA-67-15 and 00-13-02-31-E8-BA.MAC address is also called the physical
address. Under Windows, the MAC address of a computer can be displayed by typing ipconfig/all at
a Command prompt.
1.2.5. Repeater
A repeater is a device used to expand the boundaries of a wired or wireless network. With physical
media, data transmissions can only span a limited distance before the quality of the signal degrades.
Repeaters are usedto preserve signal integrity and extend the distance over which data can safely
travel by regenerating the signals they receive. Active hubs are considered as repeaters (multiport
repeaters).
1.2.6. Bridge
A bridge, also called a layer 2 switch, is a device used to create a connection between two separate
computer networks or to divide one network into segments. Creating multiple segments in a local
network reduces the network traffic making the network to be faster and more efficient. A bridge
performs its segmenting function by examining the data packet and forwarding it to other physical
segments only if necessary.
1.2.7. Router
A router is a device that joins several networks together and is responsible for routing data from
one network to another. It keeps track of the IP addresses of the computers on the networks
connected to its network interface cards and directs data packets appropriately. It is more powerful
than a bridge because instead of just choosing network segments based on previous traffic, a router
can look up the best route for a packet to take. Routers can be computers with operating systems
and special network software, or they can be other dedicated devices built by network
manufacturers. The Internet relies heavily on routers.
1.2.8. Modem
A modem (modulator/demodulator) is a device that encodes data for transmission over a particular
medium, such as telephone line, coaxial cable, fiber optics, or microwaves. It converts digital signals
from a computer to analog signals or waveform for transmission over a medium (modulation) and
converts analog signals from the medium to digital signals understandable by the
computer(demodulation).
Common types of modems are:
Dial-up Modem
Cable Modem
DSL Modem
Sat modem
93
Advanced Level Computer Science/ICT
1.2.9. Multiplexer
A multiplexer abbreviated MUX, is a device that takes input signals from different sources and
transmits them over a single transmission line. This process is known as multiplexing. There are
different types of multiplexing:
Frequency-division multiplexing (FDM), in which the carrier bandwidth is divided into sub
channels of different frequency widths, each carrying a signal at the same time in parallel.
Time-division multiplexing (TDM), in which the multiple signals are carried over the same
channel in alternating time slots.
Code-division multiplexing (CDM), in which the multiple signals are carried over the same
channel but every signal is coded differently.
Orange and MTN use a combination of FDM and TDM called GSM while Camtel uses CDMA.
1.2.10. Cables
Cables are used to link computers in a LAN. There are three types of cables commonly used:
Coaxial cable
Twisted pair cable
Fiber optic cable
1.2.11. Gateway
A gateway is a device that connects two dissimilar computer networks using direct and systematic
translation between protocols. A gateway translates outgoing network traffic to the protocol needed
by the destination network. The term gatewayis also sometimes loosely used to describe any device
that acts as the entry or exit point for a network.
1.3.1. BusTopology
In bus topology, all computers are connected to a single cable (trunk or backbone) known as bus, by
a transceiver either directly or by using a short drop cable. Bus transmits in both directions such
that any transmission can be received by all stations. All ends of the cable must be terminated, that
is plugged into a device such as a computer or terminator, to avoid signals from bouncing back.
Bus topology
94
Advanced Level Computer Science/ICT
a. Advantages
Easy and inexpensive to set up as little cabling is required
Easy to include additional stations without disrupting the network
Failure of one node does not affect network
b. Disadvantages
High rate of data collision
Fails if there is any damage to the bus
Any break in the bus is difficult to identify
1.3.2. StarTopology
In a star topology, all the computers are connected to a central device which could be a computer, a
hub or a switch. Any communications between computers in this topology must pass through the
central node. As such, the central node controls all the activities of the network.
Star topology
a. Advantages
Breakdown of a node does not affect the network
No disruption of the network when connecting or removing devices
It is easy to detect faults
b. Disadvantage
Failure of the central node affects the entire network
It is costly due to the amount of cables required to connect the devices
1.3.3. RingTopology
In ring topology, all the nodes are connected in the form of a closed loop such that each node is
connected to two others. It uses an empty data packet called a token and a special protocol called
token ring. Packets travel around the ring in a clockwise direction. To transmit, a node requires an
empty token.
Ring topology
95
Advanced Level Computer Science/ICT
a. Advantage
No collision as a station needs the token to transmit
Each computer acts like a repeater so signals are not attenuated
b. Disadvantage
If a node in the network fails, the entire network fails
Network is disrupted when additional stations are added
1.4.1. EthernetNetwork
Ethernet (IEEE 802.3 standard) is the most common and widely used technology to establish a local
area network. An Ethernet network is formed by physically connecting the individual computer
units to each other in a bus topology or a star topology. Ethernet’s media access policy is CSMA/CD
(Carrier Sense Multiple Access with Collision Detection).
CS: means that a station listens to (senses) the medium and transmits only if medium is idle
MA: means that any station can use (access) the medium
CD: means that each station stops transmitting immediately it senses a collision
When a collision is detected, the two stations involved will retransmit after a random time wait
created by a backoff algorithm.
96
Advanced Level Computer Science/ICT
1.4.6. WirelessNetworkStandards
Wireless networks are established without physical wiring techniques involved. They use radio and
infrared signals and are based around one of these technologies: Bluetooth, Wi-Fi, WiMax,
terrestrial microwaves and satellite.
a. Bluetooth
Bluetooth is a low power, short-range wireless technology largely used to interconnect computing
devices into a personal area network. It is based on IEEE standard 802.15 which gives specifications
for Wireless Personal Area Network (WPAN).
b. Wi-Fi
Wi-Fistands for Wireless Fidelity. It is based on a set of wireless networking technologies known as
802.11. These include 802.11b, 802.11a, 802.11g and 802.11n. The range of Wi-Fi network
transmission is about 30-40m indoors and up to about 100m outdoors.
The table below shows the different 802.11 standards for wireless networking.
c. WiMax
WiMax stands for Worldwide Interoperability for Microwave Access. It is based on IEEE standard
802.16 and facilitates high speed wireless network links to both fixed and mobile devices. The range
of a WiMax wireless connection is around 3-10km.WiMax service providers are now just entering
the market, offering customers an alternative to a DSL Internet connection.
97
Advanced Level Computer Science/ICT
users of the network. There are many different kinds of servers, and one server can provide several
functions. For example, there are file servers, print servers, mail servers, database servers and Web
servers. Users run applications on client workstations which rely on servers for resources such as
files, devices and even processing power.
Internet services are organized according to a client/server architecture. Client programs, such as
Web browsers and file transfer programs create connections to servers, such as Web and FTP
servers. The clients make requests and the server responds to the requests by providing the
services requested by the client.
1.5.2. Peer-to-PeerArchitecture
Peer-to-peer (P2P) is a network configuration in which all the workstations (computers) have equal
capabilities and responsibilities. Each workstation acts both as a server and a client. This means that
any computer on the network can provide services to any other computer. Peer-2-peer is usually
implemented where strict security is not necessary. P2Pnetworks are generally simpler and less
expensive, but they usually do not offer the same performance under heavy loads.
Remark A hybrid network combines client/server and peer-to-peer architectures. It is the most
commonly used network architecture.
1.6.2. Limitations
Purchasing the network cabling and file servers can be expensive.
Managing a large network is complicated.It requires training and a network manager usually
needs to be employed.
If the file server breaks down the files on the server become inaccessible. Email might still
work if it is on a separate server. The computers can still be used but are isolated.
Viruses can easily spread to other computers throughout the network, if one computer is
infected..
There is a danger of hacking, particularly with wide area networks. Security procedures are
needed to prevent such abuse, eg a firewall.
98
Advanced Level Computer Science/ICT
2. Data Communication
Data communication refers to the exchange of data between two devices via some form of
communication channel. In data communication the following basic terms are frequently used:
Data: a collection of facts in raw form that becomes information after processing.
Signal: an electric or electromagnetic encoding of data.
Signaling: propagation of signals across a communication channel.
Transmission: sending of data from one place to another by means of signals.
Analogue signal
99
Advanced Level Computer Science/ICT
2.1.2. DigitalSignals
A digital signal is one in which information is represented as a sequence of binary values 0 and
1.These two values represent two conditions, on or off, corresponding to two known levels of
voltage or current.
Digital signals do not continuously vary as analogue signals. Signals are transmitted within the
computer as digital signals. Systems that use digital technology are known as baseband systems.
Digital signal
2.2.2. BroadbandSystem
A broadband system is a system that supports multiple transmissions via multiple frequency
channels. In a broadband system, data is sent in the form of an analog signal where each
transmission is assigned a portion of the bandwidth. Broadband communication is unidirectional, so
in order to send and receive, two pathways are needed. This can be accomplished either by
assigning a frequency for sending and assigning a frequency for receiving along the same cable or by
using two cables, one for sending and one for receiving.
2.3.1. Simplex
In simplex mode, signals are transmitted in only one direction. The flow of information is
unidirectional from transmitter to receiver always. Examples are television broadcasting, computer
to the printer connection and CPU to monitor communication.
A B
100
Advanced Level Computer Science/ICT
2.3.2. HalfDuplex
In half duplex mode, signals can be transmitted in both directions but only one way at a time. The
flow of information is bidirectional but information can only be sent if it is not being received. It is
suitable for data transmission between a computer and dumb terminals. An example is the police
radio (walkie-talkie).
A B
2.3.3. FullDuplex
In full duplex mode, signals can be transmitted in both directions simultaneously. The
communicating devices can transmit at the same time. The flow of information is bidirectional. It is
suitable for interactive systems. An example is the telephone.
A B
2.3.4. ParallelTransmission
Parallel transmission is the method of transferring several bits at the same time over separate
channels. For example, eight separate channels will be required if a block of eight bits is to be
transmitted in parallel. Parallel transmission is fast but it is suited only for short distances as cabling
for long distances will be expensive. It is mainly used for connections within the computer and for
connecting the computer to the printer.
101
Advanced Level Computer Science/ICT
Serial transmission is slower than parallel transmission but it is suited for long distances. It is
cheaper as only one transmission line is required. Synchronous transmission is faster than
asynchronous transmission because fewer bits have to be transmitted; only data bits and no extra
control bits. For this reason it is the choice for network communications links.
2.4.1. PacketSwitching
Packet switching is a switching method in which the message to be transmitted is broken into small
data packets and sent over the network. Each packet contains a portion of data and some control
information. The packets may take different routes to arrive their destination and they may arrive in
any other. On arrival, they are put back into order and the message is reconstituted. Each packet is
sent with a header address which tells what its destination is. The header address also describes the
sequence for reassembly at the destination. One packet contains information on how many packets
should be arriving. If a packet fails to arrive, the destination computer sends a message to the
sender’s computer asking it to send the missing packet again. This method is suitable for
transmission of data.
2.5. TransmissionMedia
A transmission medium is the physical pathway that connects computers and other devices on a
network. Each transmission medium requires specialized network hardware that is compatible with
that medium, and most networks need to use a combination of transmission media types selected
based on the network's needs.There are two categories of transmission media: guided and unguided
media.
102
Advanced Level Computer Science/ICT
a. Coaxial Cable
Coaxial cable consists of an inner core and an outer flexible braided shield, both of conductive
material separated by an insulator. The braided shield prevents the cable from picking up or
emitting electrical noise. There are two types of coaxial cable:
thinnet and
thicknet.
Coaxial cable
To connect coaxial cable to devices, we need coaxial connectors. The most common type of
connectors used today is the Bayone-Neill-Concelman, or BNC connector.
Category 1: These are used in telephone lines and low speed data cable.
Category 2: These cables can support up to 4 mps implementation.
Category 3: These cable supports up to 16 mps and are mostly used in 10 mps.
Category 4: These are used for large distance and high speed. It can support 20mps.
103
Advanced Level Computer Science/ICT
Category 5: This is the highest rating for UTP cable and can support up to 100mps.
UTP can be connected as straight through or crossover. A straight-thru cable has identical ends. A
crossover cable has different ends.
Optic fiber
The light source can be LED (light emitting diode) or LD (laser diode)
2.5.2. UnguidedMedia
Unguided media do not use physical means to define the path to be taken. They provide a means for
transmitting electromagnetic waves but do not guide them. They are also called unbounded media.
Examples of unguided media are infrared waves, radio wavesand microwaves.
a. Infrared
Infrared uses transmitters/receivers (transceivers) that modulate non-coherent infrared light.
Infrared signals do not penetrate walls as such transceivers must be within line-of-sight either
directly or via reflection. Line of sight is a type of propagation that can transmit and receive data
only where transmit and receive stations are in view of each other without any sort of an obstacle
between them.
b. Radio waves
Radio wave systems transmit signals by modulation of electromagnetic waves with frequencies
below that of visible light. Radio waves carry information by systematically changing some property
of the radiated waves such as amplitude (AM radio), frequency (FM radio) and phase. Radiowaves
are omnidirectional.This means that signals spread out in all directions and can be received by
many antennas.
c. Microwaves
104
Advanced Level Computer Science/ICT
Microwaves are electromagnetic radiations beyond the frequency range of radio and television.
There are two types of microwave systems: terrestrial microwave systems and satellite systems.
Satellite systems use communication satellites to solve the problem posed by the earth’s
curvature to terrestrial microwave systems. A communication satellite is a microwave relay station
placed in outer space. A microwave signal is transmitted from earth to the satellite which amplifies
the signal and sends it back to earth. The earth station transmits the signal to the satellite on an up-
link, on one frequency and the satellite repeats those signals on a down link which is on another
frequency.
Disadvantages
o Line-of-sight will be disrupted if any obstacle, such as new buildings, are in the way
o Signal absorption by the atmosphere. Microwaves suffer from attenuation due to
atmospheric conditions.
o Towers are expensive to build
2.6. TransmissionChecks
Network data transmissions often produce errors, such as toggled, missing or duplicated bits. As a
result, the data received might not be identical to the data transmitted, which is obviously a bad
thing. Because of these transmission errors, network protocols very often use error-detection codes.
Examples of error-detection codes include parity checking, checksums and cyclic redundancy
checks.
105
Advanced Level Computer Science/ICT
2.6.1. ParityChecking
Parity checking refers to the process of using a parity bit to check that data has been transmitted
accurately. A parity bit is an extra bit transmitted with a data unit that will be used to check its
integrity. There are two types of parity: odd parity and even parity.
In odd parity, the parity bit is added such that the total number of bits at 1, in the data unit, is an
odd number.
In even parity, the parity bit is added so that the total number of 1s is an even number.
Example: What are the parity bits for the following data units in odd parity?
Example 2: What are the parity bits for the following data units in even parity?
2.6.2. Checksum
A checksum or hash sum is a count of the number of bits in a transmission unit that is included with
the unit for the purpose of detecting errors that may have been introduced during transmission. The
checksum or hash sum may be computed according to the number of set or unset bits in the
message. On reception, the receiver applies the same checksum function/algorithm to the message.
If the checksum obtained matches the one sent, the transmission is considered to be successful and
error-free.
106
Advanced Level Computer Science/ICT
more intermediate routers, the packet is received at each intermediate router in its entirety, stored
there until the required output line is free, then the packet is forwarded.
2.7.2. Interrupt
An interrupt is a signal to the processor emitted by hardware or software indicating an event that
needs immediate attention. An interrupt alerts the processor of a high-priority condition requiring
the interruption of the current task the processor is executing. Interrupts are used to handle such
events as data receipt from a modem or network, or a key press or mouse movement.
2.7.3. Polling
Polling is the process by which the central computer or communications controller in a network,
"polls" or asks each device in the network if it has a message to send and then allows each in turn to
transmit data. Access and control of star network typically is maintained by a polling system.
2.7.4. Handshaking
Handshaking is the process by which two devices initiate communications. It begins when one
device sends a message to another device indicating that it wants to establish a communications
channel. The two devices then send several messages back and forth that enable them to agree on a
communications protocol.
2.8. CommunicationProtocols
For proper communication in a network, different entities must speak the same language. There
must be mutually acceptable conventions and rules about the content, timing and underlying
mechanisms. These conventions and associated rules are referred as protocols.
Definition: A protocol is a set of rules and conventions that govern how devices on a network
communicate.
The need for a protocol is obvious: it allows different computers from different vendors and with
different operating characteristics to ‘speak the same language’. The same protocols must be
followed by each machine involved in the communication in order for the receiving host to be able
to understand the message. A protocol may be physical or logical.
2.8.1. PhysicalProtocols
Physical protocols are concerned with how a device connects to a medium. They ensure that a
device connected to a medium can transmit through the medium. They make sure that the layout of
pins on the connectors is the same and that devices are correctly connected and configured. Few
examples of physical protocols are 802.11 for Wi-Fi connections and DSL for broadband.
107
Advanced Level Computer Science/ICT
2.8.2. LogicalProtocols
Logical protocols are concerned with data handling. They ensure that data are in the right format for
the application, the bit rates match at both ends, and the same error correction is used. Examples of
logical protocols are TCP/IP, HTTP, POP3, FTP, SMTP and WAP.
7 Application Layer
6 Presentation Layer
5 Session Layer
4 Transport Layer
3 Network Layer
1 Physical Layer
These layers can be recalled using the
OSI Reference Model following mnemonics: All People Seem
To Need Data Processing. (Layers 7 - 1)
Layer 7: Application
It provides network services directly to the user’s applications such as a web browser or e-mail
client. This layer is said to be “closest to the user”. Examples of protocols that operate at this layer
are: TELNET, HTTP, FTP, SMTP and POP.
Layer 6: Presentation
The Presentation layer represents the data in a particular format to the Application layer. It defines
encryption, compression, conversion and other coding functions. Examples of specifications defined
at this layer are: GIF, JPEG, MPEG, MIME and ASCII.
Layer 5: Session
It establishes, maintains and terminates end-to-end connections (session) between two applications
on two network nodes. It controls the dialogue between the source and destination nodes, which
node can send when and for how long. Examples of protocols that operate on this layer are: RPC,
NETBIOS and X.225
108
Advanced Level Computer Science/ICT
Layer 4: Transport
It is responsible for end-to-end delivery of entire messages. It allows data to be transferred reliably
and uses sequencing to guarantee that it will be delivered in the same order it was sent. It also
provides services such as error checking and flow control. Examples of protocols at this layer are:
TCP, UDP, NETBEUI and SPX.
Layer 3: Network
It is responsible for path determination, routing, and the delivery of packets across internetworks. It
is also responsible for addressing (also known as logical addressing) for example IP addressing.
Examples of protocols at this layer are: IP, IPX and ICMP.
Examples of devices that operate at this level are Layer-3 switches and routers. WAPs (wireless
access points) with built-in routing capabilities also act at this layer.
Layer 1: Physical
This layer communicates directly with the communication medium. It is responsible for activating,
maintaining and deactivating the physical link. It defines electrical and optical signaling, voltage
levels, data transmission rates, as well as mechanical specifications such as cable lengths, and
connectors, the amount of pins and their functions. Examples of devices that operate at this layer
are: hubs, repeaters, and NICs.
These layers can be recalled using the following mnemonics: All People Seem To Need Data
Processing. (Layers 7 - 1)
3. The Internet
3.1. Brief History
Many years ago, the military of the United States of America desired to interconnect or link their
computers in order to better understand and manage information and communication with respect
to enemy attacks in times of crisis. In the year 1969 the Department of Defense (DoD) then
developed an experimental network called the Advanced Research Project Agency Network
(ARPANet)
In the year 1980, the National Science Foundation of the United States of America then developed
the technology of ARPANet to produce the National Science Foundation Network (NSFNet) which
109
Advanced Level Computer Science/ICT
now enabled universities and other school establishments in the USA to be interconnected. After a
great deal of work, a network which enabled the transfer of large amounts of information at very
high speed which is today called the Internet was developed.
The Internet can be defined as a worldwide/global system of interconnected computer networks. It
is the network of networks in which users can view information on the World Wide Web, exchange
electronic mail, participate in electronic discussion forums (newsgroups), send files from any
computer to any other and even use each other’s computers directly if they have appropriate
passwords. Another name for the Internet is information superhighway.
110
Advanced Level Computer Science/ICT
3.2.3. BroadbandCable
TV channels only take up 6MHz of cable bandwidth each, which usually leaves several hundred MHz
available. This additional space on cable is used for high-speed Internet connection. Information
from the Internet travels through the cable as a single TV channel. Just as with DSL, cable Internet
requires a special transceiver (cable modem) which allows information to be sent and received on
frequencies not used by TV channels. The cable modem provides one or more LAN interfaces,
usually Ethernet or USB which connect directly to a client or a device such as a hub, switch, or
wireless router to allow additional clients or entire networks to use the same connection. The cable
modem is also equipped with connections for TV and radio.
Application Layer
Application Layer HTTP FTP SMTP DNS RIP
Presentation Layer
111
Advanced Level Computer Science/ICT
During a transmission, a message travels down all network layers at the source machine. Before
sending a message to the next layer, each layer places it in an envelope of overheadinformation
related to that layer. This process is called encapsulation. Encapsulation at each layer produces
adata unit called protocol data unit (PDU).
At the receiving end, the message travels up through the network layers, each layer removing the
envelopes added when the message was sent. So, upon its receipt, the message is in its original state.
3.3.2. InternetLayer
This layer is responsible for packaging, addressing and routing of packets. The PDU at this layer is
called datagram or packet.
Core Internet layer protocols are: IP, ARP, ICMP and IGMP.
a. Internet Protocol
Internet Protocol (IP) specifies the format of packets and the addressing scheme. All computer
devices (desktops, laptops, PDAs, phones, tablets) connected to the Internet, have IP addresses by
which they are identified.
Definition: An IP address is a unique identifying number given to every single computer on a TCP/IP
network.
Two versions of IP addresses are available: IPv4 that uses 32 bits and IPv6 that uses 128 bits.
An IPv4 is made up of four sets of numbers separated by dots such as 123.23.168.22. This
notation is known as dotted decimal notation. Each of the four numbers separated by dots can
be any number from 0 to 255, making for a total of 4.3 billion potential IPv4 addresses (i.e.
255×255×255×255).
112
Advanced Level Computer Science/ICT
IP addresses are assigned manually (by an administrator) or automatically (by DHCP or APIPA). An
IP address is also known as a logical address.
3.3.3. TransportLayer
The transport layer is responsible for sequencing and transmission of packets, acknowledgment of
receipts, recovery of packets and flow control. In essence, it engages in host-to-host transportation
of data packets and the delivery of them to the application layer. A transport layer PDU is called
segment.
Core protocols at this layer are TCP and UDP.
a. TransmissionControl Protocol
TCP is aconnection-orientedreliable protocol used in the accurate transmission of large amounts of
data. Data packets are verified using checksums and retransmitted if they are missing or corrupted.
The application plays no part in validating the transfer.
3.3.4. ApplicationLayer
The application layer provides user applications with the ability to access the services of the other
layers. Some protocols of this layer are HTTP, FTP, POP, SMTP, Telnet, IMAP and WAP.
113
Advanced Level Computer Science/ICT
FTP is a standard for transferring files between a server and a client on a TCP/IP network. It
provides the ability to upload and download files between hosts on the network.
d. PostOfficeProtocol
POP is a standard protocol for delivering e-mails to personal computers.There are different versions
of the post office protocol indicated by POPn where n = 1, 2, 3 or4.
e. Telnet
Telnet is a protocol that allows a computer on the network to be accessed remotely. It provides the
ability to login into a remote host and administer the machine. Using Telnet a computer can be used
as a terminal on another.
f. WirelessApplicationProtocol
WAP is a protocol which runs on mobile phones and provides a universal open standard for
bringing Internet content to mobile phones and other wireless devices.
Assignment: Give the full meaning of the following protocols and state their functions.
i) IMAP
ii) RIP
iii) DNS
Definition: A communication port is a 16-bit number that identifies an application on the Internet or
TCP/IP network.
Popular Internet application protocols are associated with well-knownportsassigned by the Internet
Assigned Number Authority (IANA). Sample TCP port numbers are:
23 Telnet
25 SMTP
80 HTTP 114
110 POP
Advanced Level Computer Science/ICT
Ports are usually combined with IP addresses to form a socket. For example 127.102.10.0:80.
Example 1: http://www.bgsmolyko.edu/Ls3,4/ict796/intenet.pdf
http is the protocol used (hypertext transfer protocol)
www.bgsmolyko.edu is the domain name (the machine at BGS Molyko that hosts the website)
Ls3,4/ict796/internet.pdf is the path of the document (resource) on the host computer. Ls3,4 is
the folder, ict796 is the subfolder and internet.pdf is the file(resource).
Example 2: www.minsup.gov.cm
gov is the top level domain which specifies that the URL is for a government institution.
cm specifies the country in which the URL is hosted or the country in which the institution is
found.
b. Web Browser
A web browser (or simply browser) is a computer program that enables a user to read hypertext in
files or on the World Wide Web. Popular browsers include Mozilla Firefox, Microsoft Internet
Explorer, Opera Mini and Netscape.
115
Advanced Level Computer Science/ICT
c. Search Engine
A search engine is a computer program that searches for specific words on the World Wide Web and
returns a list of documents in which they were found. Examples of search engines include Google
and yahoo.
3.5.2. ElectronicMail
Electronic mail or e-mail (email) is a means of sending messages, text, and computer files between
computers via the Internet. To send and receive e-mails, you need an Internet connection and an e-
mail account which can be created within a webmail service such as Yahoo, Hotmail or Gmail. When
you create an e-mail account, you are given a unique email address that gives you access to your
mail box. An email address is made up of two parts separated by the symbol @ pronounced “at”. For
example [email protected].
In the above address,
bgsmolyko is the user ID, user name or login
yahoo.com is the domain name. The domain specifies the mail server (computer) on which
the mail box is located.
The part of the domain name after the dot is called top-level domain, and specifies the type of
organization or the country the host server is located. Some common top-level domains are:
o .com - for commercial enterprises
o .edu - for educational institutions and universities
o .gov - for United States government agencies
o .net - for organizations such as Internet Service Providers
o .org - for non-commercial organizations
3.5.3. InstantMessaging
Instant messaging is a live (or real time) communication which occurs when brief text messages are
exchanged instantly over the Internet. Instant Messaging requires that both users be on-line at the
same time. Common IM applications are AOL Instant Messenger, Yahoo Messenger and Microsoft
MSN messaging.
3.5.4. InternetTelephony
Internet telephony or voice over IP (VoIP) is the transmission of voice telephone conversations
through the Internet or IP networks. It allows users to have voice-talk with others. The telephone
calls are digitized and transmitted through the Internet. Internet telephone services can be mainly
categorized into net-to-net and net-to-phone telephony.
In net-to-net telephony, both caller and receiver must be online. When both are online, one dials the
other person’s phone number. If they accept the call, then voice communication is established.
In net-to-phone, only one person has to be online. This person dials the other person’s phone
number and the latter receives a ring on their phone. Yahoo messenger and Skype provide services
for both types.
116
Advanced Level Computer Science/ICT
3.5.5. InterpersonalComputing
Interpersonal computing refers to person-to-person interactions facilitated by websites that enable
collaborative content creation, sharing and manipulation. Interpersonal computing involves: blogs,
social networks, wikis and viral video sites.
a. Blogs
A blog (web log) is a chronological, journal-style website which its author (or "blogger") maintains
like an online diary, with regular entries of commentary, descriptions of events, or other material
such as graphics or video. Many blogs provide commentary or news on a particular subject; others
function as more personal online diaries. They also provide the readers with the ability to leave
comments in an interactive format.
c. Wikis
Wikis are websites that allow visitors to easily add, remove and edit content, hence enabling the
collaborative authorship of comprehensive documents. The best example of a wiki is the multi-
lingual, web-based encyclopediaWikipedia, and which currently includes over two million articles.
3.5.6. ElectronicCommerce
E-commerce refers to the buying and selling on the Internet. Different models of e-commerce exists:
business-to-business, business-to-consumer, business-to-government and m-commerce
a. Business-to-Business
B2C model sells goods or services to the consumer, generally using online catalog and shopping
cart transaction systems. For example, an online pharmacy giving free medical consultation and
selling medicines to patients is following B2C model. Amazon is an example of one of the first and
still one of the most successful B2C e-commerce companies.
b. Business-to-Business
117
Advanced Level Computer Science/ICT
B2B describes commerce transactions between businesses, such as between a manufacturer and a
wholesaler, or between a wholesaler and a retailer. In this form, the buyers and sellers are both
business entities and do not involve an individual consumer.
c. Business-to-Government
B2G is a derivative of B2B marketing. B2G sites provide a platform for businesses to bid on
government opportunities which are presented as solicitations requests for proposal (RFPs) to
tender.
d. M-Commerce
M-commerce refers to the use of mobile devices for conducting transactions. The mobile device
holders can contact each other and can conduct the business. Even the web design and development
companies optimize the websites to be viewed correctly on mobile devices.
Some e-commerce websites are: www.bruneiair.com for airline ticket bookings, www.amazon.com
for sales of books and magazines, www.brumedia.com/shop for sales of computers, shirts, and
cameras
118
Advanced Level Computer Science/ICT
An intranet can be seen as a private version of the Internet. To access an intranet, some form of user
authentication is usually required. External access to an intranet is not always provided.
An extranet is an interconnection of two or more intranets. It allows an organization to share
information with other organizations using Internet standards but with security features preventing
access to others.
<HTML>
<HEAD>
<TITLE>Page title here</TITLE>
</HEAD>
<BODY>
Page content here.
</BODY>
</HTML>
119
Advanced Level Computer Science/ICT
Remark Once an HTML document hasbeen saved, it can now be opened as a web page using a web
browser.
To edit the page, go back to the text document. Make the changes and save the document. In the web
page, click “reload” or “refresh” to apply the changes.
Tags Description
<b> … </b> or Bolds the text between the
<strong> … </strong> opening and closing tags
<i>...</i> or
Puts text in italics
<em>...</em>
<u> … </u> Underlines text
<font> … </font> Sets the appearance of the
<font size=? text in your page. Can be
color=#0000FF> … used with "size", "color" and
</font> "face" attributes.
<blink> … </blink> Causes text to blink
Centers text or any item or
group of items place
<center> … </center>
between its open and
closing tags
<marquee> …
Causes text to navigate
</marquee>
120
Advanced Level Computer Science/ICT
Example 1:
<html>
<head>
<title>My First Web Page</title>
</head>
<body>
<strong>This text is bold</strong><br>
<b>This text is bold too</b><br>
<em>This text is in italics</em><br>
<i>This text is in italics too</i><br>
<u>This text is underlined</u><br>
<b><i>This text is bold and in italics</i></b><br>
<strong><em><u>This text is bold, underlined and in italics</u></em></strong>
</body>
</html>
Example 2:
<html>
<head>
<title>MyPage</title>
</head>
<bodybgcolor=“cyan”>
<font type=“Monotype corsiva” size= “12” color=“blue”
</body>
</html>
Remark! Tags are case insensitive but it is advisable to write them in lower case.
All attribute values must be written within double quotes.
121
Advanced Level Computer Science/ICT
Example:
<html>
<head>
<title>Heading</title>
</head>
<body>
<h1>Level 1 heading</h1>
<h2>Level 2 heading</h2>
</body>
</html>
122
Advanced Level Computer Science/ICT
Images are inserted in the page with the use of the image tag <img>. It has no closing tag and can be
used with the attributes src which specifies the source of the image, align, top and width.
Example:
<img src= “image path” align=“top” height=“40” width=“30”> … </img>
<img src=“logo.jpg”>
<img src= “mypict.gif>
Example:
<table>
<tr><td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr><td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>
123
Advanced Level Computer Science/ICT
X. DATABASE DESIGN
Introduction
A database is an organized collection of related data stored in a way that it can be easily retrieved
and manipulated. A telephone directory, a library catalogue and a class register are examples of
manual or paper-based database systems. A paper-based database requires much paper as the
database becomes larger, making it difficult to manipulate the database. The problems caused by
paper-based systems are solved by the development of computer-based systems.
The capacity for computers to store large amounts of data and their ability to quickly and efficiently
retrieve the data makes them ideal for creating and using electronic or computerized databases. A
computerized database refers to a collection of related files that are digitized. Computerized
databases are created using database software called database management systems (DBMS).
1. Database Models
The solution to these problems is to divide the data into logical groups and store the data in multiple
tables, then connect (relate) the tables to each other. This results to a Relational database.
124
Advanced Level Computer Science/ICT
An object-oriented database tries to keep the advantages of the relational model and at the same
time allows applications to access structured data.
2. Database Modeling
2.1. DatabaseNormalization
Database normalization is the process of organizing the fields and tables of a relational database to
minimize redundancy and dependency. Normalization usually involves dividing large tables into
smaller and less redundant tables and defining relationships between them. Normalization works
through a series of stages known as normal forms. In order to achieve one level of normal form,
each previous level must be met.
In the above table, Subject does not depend on StudID. In this case, a different table is created for
subject with its own primary key and a relationship is created between the two tables.
2.2. Entity-RelationshipModeling
When a relational database is to be designed, an entity-relationship model is drawn at an early stage
and developed as the requirements of the database and its processing become better understood.
125
Advanced Level Computer Science/ICT
Definition: An E-R model is a diagram which uses basic graphic symbols to show the organization of
and relationships between data in a database.
An E-R diagram serves as a schema diagram for the required database. A schema diagram is any
diagram that attempts to show the structure of the data in a database.
Name
Number
DOB Street
An E-R diagram
The basic elements of an E-R diagram are entity sets, attributes and relationship types.
2.2.1. EntitySet
An entity is a person, place, concept or thing for which we intend to collect data. For example, a
customer, an employee, a book, an appointment.
A group of entities that share the same properties is an entity set.An entity is therefore a member or
an instance of an entity set. In an E-R diagram, an entity set is represented by a rectangle. In the
above E-R diagram, PERSON and HOUSE are entity sets
2.2.2. Attribute
An attribute is a fact about an entity or a property that describes an entity. For example, a person’s
name, date of birth or gender, a vehicle’s model, color or brand. Attributes store the actual data we
want to keep about each entity within an entity set. An attribute is represented by an ellipse. In the
above E-R diagram, name and date of birth are attributes of the entity set PERSON while Number
and Street are attributes of the entity set HOUSE.
2.2.3. RelationshipType
A relationship type is a named association between entities. A person (entity) owns (relationship) a
house (entity), a teacher (entity) teaches (relationship) a subject (entity). Normally, individual
entities have individual relationships of the type between them but in an E-R diagram, this is
generalized to entity sets and relationship types. For example, the entity set PERSON is related to
the entity set HOUSE by the relationship type OWNS.A relationship type is represented by a
diamond.
126
Advanced Level Computer Science/ICT
The degree of a relationship type is the number of entity sets involved in the relationship. It can be
unary, binary, ternary or n-ary.
A unary relationship type is one that involves entities from a single entity set. E.g. the
relationship MANAGES between entities within the entity set EMPLOYEE.
EMPLOYEE Manages
A binary relationship type is a relationship between entities from two different entity sets. An
example is the relationship OWNS in the E-R diagram above.
A ternary relationship type is one that involves entities from three different entity sets. An
example is a LECTURER who teaches a certain COURSE in a DEPARTMENT.
DEPARTMENT
In the relationship OWNS between PERSON and HOUSE, a person can own zero or many
houses. Therefore, the cardinality of PERSON in the relationship OWNS is many while the
optionality is zero.
On the other hand, a house is owned by one person. The cardinality of HOUSE in the inverse
relationship IS_OWNED_BY, is one while the optionality is one. The relationship OWNS is
therefore described as a one-to-many (1:N) relationship.
127
Advanced Level Computer Science/ICT
(1,1) (0,N)
PERSON Owns HOUSE
(1:N) relationship
In the relationship RECEIVES between STUDENT and SLIP, each student receives one andonly
one result slip. The cardinality of student is one and the optionality is one. Each result slip is
issued to one and only one student. The cardinality of SLIP is one and the optionality is one.
This relationship is described as one-to-one (1:1).
(1,1) (1,1)
STUDENT Receives SLIP
(1:1) relationship
In the relationship TEACHES between TEACHER and SUBJECT, a teacher teaches one or many
subjects. The cardinality of TEACHER is many and the optionality is one.
A subject is taught by one or many teachers. The cardinality of SUBJECT in the inverse
relationship IS_TAUGHT_BY, is many and the optionality is one. This relationship is described
as many-to-many (M:N).
(1,M) (1,N)
TEACHER Teaches SUBJECT
(M:N) relationship
The primary key of the link entity is a composite key that consists of the primary keys of the entities
TEACHER and SUBJECT.
The above representation of an E-R diagram is the Chen Convention. Another way of representing E-
R diagrams is the crow’s foot notation that uses three symbols to show cardinality ratios. Here, a
circle means zero, a line means one and a crow’sfoot means many. The cardinality is shown next to
the entity type and the optionality (if shown at all) is shown behind it.
128
Advanced Level Computer Science/ICT
2) A database will be made to store information about patients in a hospital. On arrival, each
patient’s personal details (name, address, and telephone number) are recorded where
possible, and they are given an admission number. They are then assigned to a particular
ward (Accident and Emergency, Cardiology, Oncology, etc.). In each ward there are a number
of doctors and nurses. A patient will be treated by one doctor and several nurses over the
course of their stay, and each doctor and nurse may be involved with several patients at any
given time.
From the description, draw a corresponding E-R diagram showing all entity sets, attributes,
relationship types and cardinality ratios.
129
Advanced Level Computer Science/ICT
These components are called database objects. One or more of these components are formed when
a database is created. These components are stored in a single database file.
3.1.1. Tables
A table is an area of the database where information is stored. Tables organize data into columns
(called fields) and rows (called records). Example: a database storing information about books and
authors for a library could have a “BOOKS” table to store information about books (title, publisher,
Year, etc) and an “AUTHORS” table to store information about authors (name, birth date, birth place,
etc).
A field is a specific piece of data stored in a table. The above mentioned ‘BOOKS’ table has fields
‘Title’, ‘Publisher’, ‘Year’ etc.
Each field in a database table is assigned a data type when the field is created. The data type
determines the kind and format of the information stored in the field. Example: the “Title” field
in the “BOOKS” table will store text that will vary with each book in the database, so the data
type in this case will be text or character type.
130
Advanced Level Computer Science/ICT
Tip: You can use the Rename option at any time to rename any column. For example, you can
rename the ID column Author_ID.
3.1.2. Relationships
Relating tables reduces the unnecessary duplication of data (redundancy).The general procedure
for creating relationships in Access is to
o Determine the type of the relationship and identify the source and target tables
o Create the foreign key field(s) in the target table if they are not already present
131
Advanced Level Computer Science/ICT
For example: Let’s create a relation between the AUTHORS table and the BOOKS table.
3.1.3. Queries
A query is a command that tells the database what data the user wants to see. A query allows
information to be found and retrieved from one or more tables based on a set of search conditions
you define. For example: a query can be written specifying that the database should retrieve all the
books from the “BOOKS” table written by William Shakespeare.
To create a query,
o Click the Create tab on the Ribbon
o Click the Query Design command
o Double-click Create Query in Design View
o Select the table that you would like to base your Query on
o Click Add
o Close the Show Table window
In order to control which records are displayed, you must define criteria in a Query.
To define criteria for your query:
o Position your cursor in the criteria row in the field for which you wish to define the criteria
for
o Enter the criteria
o Click the Run Query button
3.1.4. Forms
A form is an interface that allows users to enter and view data. Forms give the ability to choose the
format and arrangement of fields. They can be used to enter, edit and display data. Forms can
retrieve data from one or more tables, and display the output on the screen.
132
Advanced Level Computer Science/ICT
NB. The form feeds the table. If you edit a record on the form, or create a new record, that data will
be passed to the table it is associated with.
3.1.5. Reports
A report is an effective way to analyze and present data in printable format using a specific layout.
Reports are the primary method of retrieving and viewing information. Using queries, reports pull
information the user has requested and either print that information or display it on screen. The
information that appears and the formatting and appearance of a report are set when the report is
created.
133
Advanced Level Computer Science/ICT
a. Integer
An integer is a whole number that can be positive, negative or zero. Examples: -3, 5, 67, -134 and
4231.
b. Real
A real is a number that contains a decimal point. Computers manipulate numbers with fractions as
floating point numbers. Examples: 3.14, 12.25 and 0.001.
c. Boolean
A Boolean data type stores one of only two values – true or false, yes or no, or on or off. Usually
these values are stored as 1 for true and 0 for false.
d. Character
A character is any letter, digit, space, punctuation mark, or symbol that can be typed on a computer.
The word "computer" for example, consists of eight characters. The phrase "data type" takes up nine
characters. A character data type stores only a single character or digit. Each character requires one
byte of space, so "computer" takes up 8 bytes (8 × 8 = 64 ����). Examples: A, 5, -, and !.
e. String/Text
134
Advanced Level Computer Science/ICT
A string is a set of characters grouped together. A string is sometimes just referred to as ‘text’. It can
contain a mixture of numbers, letters and, spaces. Numeric data stored as text is only for
representation not for calculation. Any type of alphabetic or numeric data can be stored as a string.
Examples: “Limbe City”, “10base-2” and “36.85”.
f. Date/ Timestamp
Date and timestamp are data types for storing date and time respectively. The format used for date
is either dd-mm-yy or mm-dd-yy and hh:mm:ss or ss:mm:hhfor time.
g. Container
A container is a data type used for storing images, video, sound or another type of ‘complex’ file. In
some languages, binary large object (blob) is used rather than container.
1.2. DataStructures
A data structure is a way of organizing and storing data in memory so that it can be used efficiently.
Any data structure is designed to organize data so that it can be accessed and worked with in
appropriate ways. A well-designed data structure allows a variety of critical operations to be
performed, using as few resources, both execution time and memory space, as possible. Data
structures include arrays, records, stacks, queues, trees, graphs and hash tables.
2.1.1. Arrays
An array is a data structure, which allows a set of items of identical data type to be stored together
using the same identifier name. When an array is created, its dimension (size) and the type of its
elements are specified.
The above statements create an array called “Names” of five elements in C and Pascal respectively.
The size of the array is 5 and its elements are of type string.
To reference an element in an array, an index is used. An index is an integer that gives the element
at the indexed position in the array.
For example in C, Names[0] references the first element in the array Names, Names[1] references
the second element, Names[2] references the third and so on…
In Pascal, the referencing starts from 1 rather than 0.
a. One-dimensional Arrays
A one-dimensional array is an array which is declared using a single index and can be visually
represented as a list. The array “Names” above is one-dimensional.
If the array “Names” contains five elements (names), Raissa, Peter, James, Leticia and Isaac, it can be
visually represented as follows:
b. Two-dimensional Arrays
A two-dimensional array is an array which is declared using two indices and can be visually
represented as a table.
For example:
Example: Given the 2-dimensional array Tab[4][2] below, what are the elements given by the
references Tab[0][0], Tab[1][1], Tab[3][0] and Tab[2][1]?
Index [0] [1]
[0] 5 3
[1] 1 4
[2] 3 1
[3] 2 8
Each individual element can be referenced by its row and column indices. For
example:
Tab[0][0] = 5
Tab[1][1] = 4
Tab[3][0] = 2
2.1.2. Record
A record is a data structure which allows items of different types that define a particular structure
or object, to be stored together. The elements of a record are usually called fields or members.
Defining a record includes specifying the data type of each field and a name (label) by which the
field can be accessed.
For example,
Student = RECORD struct Student
Date= RECORD
Name: String {
Day: Integer
Gender: Character string Name
Month: String
DOB: Date char Gender
Year: Integer
End RECORD Date DOB
End RECORD
}136
Advanced Level Computer Science/ICT
The above Date record has a numeric field Day, a text field Month and a numeric field Year. The
Student record has fields Name, Gender and DOB which is of type Date. The table below gives
examples of student records.
Name Gender DOB
Each row in the table corresponds to a different record. This table has 5 records.
A field in a record is referenced as follows:
RecordName.fieldName = “”
Raissa.DOB= 01 Apr 1996
Record data structures are always used in association with arrays. That is, we define an array whose
elements are of type record. When this is done, we have an array of records.
For example: let’s define an arrayClassList, which stores information about the students in the table
above.
2.1.3. Stack
A stack is a linear list in which items are added and removed from the same end (head). Items being
added and removed from the same end means that the last item to be added will be the first to be
removed. As such stacks are also called last in, first out (LIFO) lists as they use the LIFO principle.
(FILO)
Stack operations are:
137
Advanced Level Computer Science/ICT
Application of stacks:
� × � + �?
��+�=
�× �+� ?
2 × 6 + 5 = 17?
2×6+5 = ��
2 × 6 + 5 = 22?
Infix notation requires the use of order of precedence of operators and parentheses making it
complicated and difficult for computers to evaluate expressions in this form.
To ease evaluation of arithmetic expressions, other notations are used: the prefix and postfix
notations.
In prefix notation also called polish notation, operations are written before the operands. For
example the expression (� × �) + � will be written in prefix notation as
� × � + � = × �� + �
= +× ���
In postfix notation also called reverse polish notation, operands come before operators. For example
� × � + � = �� × + � = �� × � + 2 × 3 + 1 = 23 × 1 +
Also,
� × � + � = � × �� + = ��� +× 2 × 3 + 1 = 231 +×
138
Advanced Level Computer Science/ICT
Prefix and postfix notations do not require parentheses or precedence rules. Calculators use postfix
notation to evaluate arithmetic expressions. A simple way to understand is by using the following
expression: Pre A InB Pos.
To convert from infix to prefix or postfix, priorities are assigned to operators as follows:
��������( × ) = �������� / > �������� + = �������� ( − ) and the following rules are used.
- When an operand lies between two operators, it associates with the operator that has higher
priority.
- When an operand lies between operators of same priority, it associates with the operator on
the left.
Stack[empty]
Output: [ ]
Read A push it into stack stack[A] output: [� ]
Read + stack[+] output: [� ]
Read ( stack[+(] output: [ ]
Read ( stack[+((] output: [ ]
Read B stack[+((] output: [ �� ]
Read * stack[+((*] output: [ �� ]
Read C stack [+((*]output: [���]
Read ) stack [+(] output: [��� × ] pop until you meet an opening )
Read / stack [+(/] output: [��� × ]
Read D stack [+(/] output: [��� × �]
Read ) stack [+] output: [��� × �/]
stack[ ] output: [��� × �/+ ]
139
Advanced Level Computer Science/ICT
2.1.4. Queues
A queue is a linear list in which items are inserted at one end (tail/rear) and removed from the
other end (head/front) such the first item added to the queue is the first to be removed. Queues are
also called FIFO lists as they use the FIFO principle. (LILO)
Queue operations include:
Create(Q): creates a queue Q.
Enqueue(Q,x): inserts the element x to the tail of the queue Q.
Dequeue(Q): removes the first element from the head of the queue Q
Top(): checks the next element to be removed (do not remove)
IsEmpty(): checks whether the queue is empty. Returns true if it is empty and false otherwise.
Application of queues:
a. Spooling
It is a method used to place input and output on a fast access storage device, such as a disk, so that
slow peripheral devices do not hold up the processor. For example, print spooler stores output to be
printed in a queue while waiting for the user’s program to finish creating the output. The spooler
then sends the stored output to the printer at the proper speed. If new output arrives for printing, it
is added to the queue.
b. Scheduling
It is the process of determining which of the jobs in memory will be executed by the CPU. When a
job is created, it is added to a queue, the ready queue. Any other job that arrives is added to the tail
of the queue. A scheduling algorithm like round-robin is then used to allocate the jobs one by one, to
the CPU for execution.
Remark A queue in which elements can be added and removed from any end is known as a double
ended queue (Deque).
140
Advanced Level Computer Science/ICT
2.1.5. LinkedLists
A linked list is a linear list in which each element contains a pointer to the next element in the list.
Each element in a linked list is known as a node and consists of two parts: the data item and the
pointer to the next element.
A C E
Data Pointer
Linked lists make it possible to insert items in the middle of the list without moving other items to
make room.
A B E
C D P
NB: In a double linked list, every node has two pointers: one for its predecessor and another for its
successor in the list.
2.1.6. BinaryTree
A binary tree is a finite set of nodes that is either empty or consists of a root and two disjoint binary
trees called the left sub-tree and the right sub-tree. In other words, it is a non-linear linked list
where each node may point to two other nodes. Binary trees are a very efficient way of storing items
that must be searched for and retrieved quickly. Suppose, for example, that you want to store the
following names in a computer using a binary tree:
The names can be arranged into a binary tree by using the following two-step procedure:
1. Use the first name on the list as the root of the tree.
2. To find where to put each subsequent name, start at the root of the tree. If the name you are
dealing with precedes the root name alphabetically, follow the left pointer; otherwise follow the
right pointer. Proceed in this way until you come to an empty pointer; attach the name to it.
Jones
Agbor Stephen
141
Bate Peter William
Advanced Level Computer Science/ICT
The topmost node in the tree is known as the root node. Each node in a binary tree may have at most
two children or child nodes. A node that has a child is called the child's parent node (or ancestor node,
or superior). A node has at most one parent except the root node that has no parent. Nodes that
have the same parent are called siblings. Every node in a tree can be seen as the root node of the
sub-tree rooted at that node.
Nodes at the bottom most level of the tree are called leaf nodes. Since there are at the bottom most
level, they will not have any children.
Tree traversal is the process of systematically visiting all the nodes in a tree and performing some
computation. When describing a traversal strategy, we need not concern ourselves with what that
computation is. There are two methods for traversing a tree: breadth first traversal and depth first
traversal.
142
Advanced Level Computer Science/ICT
Preorder Traversal:
- Visit the root
- Traverse left subtree
- Traverse right subtree
Inorder Traversal:
- Traverse left subtree
- Visit the root
- Traverse right subtree
Postorder Traversal:
- Traverse left subtree
- Traverse right subtree
- Visit the root
2.1.7. HashTable
A hash table is an array in which data is stored at specific locations designated by a hash function. A
hash function is a function that transforms the value of a record key into an index that corresponds
to a location for storing the record. A hash function maps the set of input data to a set of integers.
Each element to be stored in the array has a unique key that is mapped by the hash function to a
numeric value that represents an index in the array.
For example,
Index Element
0 Null
Key
35 1 Agbor
34 2 Kome
3 Eyong
43
44 4 Epie
66 5 Null
6 Sama
A hash table
143
Advanced Level Computer Science/ICT
The above hash table stores the names Agbor, Epie, Sama, Kome and Eyong using the hash
functionh(k)= k mod tablesize, where k, the key of each string is the sum of its letters’ positions in
the alphabet. This means that if an element p has key k, then p will be stored at position h(k) in the
table.
Keys:
Agbor = 1+7+2+15+18=43
Epie=5+16+9+5=35
Sama = 19+1+13+1=34
Kome=11+15+13+5=44
Eyong=5+25+15+14+7=66
3. Algorithms
An algorithm is a well-defined set of step-by-step instructions for solving a problem in a finite
amount of time. A set of instructions is not an algorithm if there is no definite stopping place, or if
the instructions are too vague to be followed clearly.
A good algorithm:
- should be explicit (i.e. clear and obvious)
- should be precise (i.e. exact and accurate)
- should be unambiguous (i.e. no doubts about what to do/ only one way of interpreting the
instructions)
- should be effective (i.e. produce good results)
- should be finite (i.e. have a definite stopping place)
144
Advanced Level Computer Science/ICT
Begin
Get A
Get B
Result = A + B
Print Result
End
3.1.2. Flowchart
A flow chart is a diagram that uses graphic symbols to describe the nature and flow of steps in an
algorithm. Each step in a flowchart is followed by an arrow that indicates which step to go next. The
following symbols are used in flow charting:
a. Elongated circle: indicates the beginning (start) or end (stop) of the algorithm
Start/Stop
145
Advanced Level Computer Science/ICT
Example: flow chart for an algorithm that divides two numbers x and y.
Start
Get x, y
Is y=0
z = x/y Error
Stop
A constant is an object whose value cannot be modified in the course of the algorithm or program. A
constant is given a value that remains the same all through the program.
A literal is anything (numbers or text) that is usually written within double quotes. For example,
“Enter a number”, “The result is”.
146
Advanced Level Computer Science/ICT
3.3. BasicInstructions
Three basic instructions used in an algorithm are input, output and assignment instructions:
An input instruction allows information to be typed from the keyboard. Example: read (a, b), get
(number)
An output instruction allows:
display of information on the screen
printing of information on paper
For example: write “a is greater than b” or print “b is greater than a”
The assignment statement allows a value to be assigned to a variable.A variable can be assigned
the content of another variable, a constant, a literal, an arithmetic or Boolean expression. The
symbol used is.
147
Advanced Level Computer Science/ICT
3.4.2. SelectionControl
A selection control structure (condition control structure) chooses the instruction or instructions to
be executed based on the validity of a certain condition. Examples are IF and CASE statements.
a. The IF Statement
Explanation Condition is a Boolean expression meaning that it can take only one of two values true
or false. The condition is evaluated, if it is true, Action3 is executed. If it is false, Action 2 is executed.
Note that actions 2 and 3 could be a block statements.
E Get a, b
if (a = 0) then
Print “Error”
else
Print b/a
148
Advanced Level Computer Science/ICT
Explanation The value of variable is evaluated, if it matches with case 1, instruction 1 is executed.
If it matches with case 2, instruction 2 is executed and so on. CASE is a multiple selection structure.
It is used when an important number of choices are to be considered depending on the value of a
variable.
E Get a, b
Get op
caseop of
1: print a+b
2: print a*b
3: print a/b
4: print a-b
end case
3.4.3. RepetitionControl
The repetition (iteration) control structure executes a statement or group of statements many times
until a certain condition is reached. Repetition structures define the order of operations and the
number of repetitions. They are also called loops. Examples are, the WHILE, REPEAT and FOR loops.
statement(s); statement(s)
end while
statement
149
Advanced Level Computer Science/ICT
E Get n
i 1
while (i <= n) do
print “this is a while loop”
ii + 1
endwhile
Syntax: repeat
statement(s);
until (condition) statement(s)
Yes
?
No
statement
Explanation The statement(s) is(are) executed and the condition is evaluated. If it evaluates to
false, the statement or set statements is/are executed again. If condition evaluates to true, the
program exits the loop.
Get n
i 1
repeat
print “This is a repeat loop”
i := i + 1
until(i <= n)
Remark! The repeat loop must be executed at least once as the condition is evaluated only at the
end of the loop.
150
Advanced Level Computer Science/ICT
Explanation var (variable) is given a value low_limit or hi_limit depending on the loop, which is
automatically incremented or decremented (by 1) after each iteration of the loop. The loop stops
when low_limit becomes greater than hi_limit. In both cases, if hi_limit is less than low_limit, the loop
body is not executed at all.
E Get n
Fori 1 to n do
print “this is a for loop”
end For
Or
Get n
Fori n downto 1 do
print “this is a for loop”
end For
Exercise! Exercise! Exercise!
1) Write an algorithm that reads a number � and returns the first � numbers. n should be a
whole number greater than 0.
2) Write an algorithm that reads a number � and returns the sum of the first � numbers.
5) Write an algorithm that reads a person’s name and sex, and returns the message “good
morning Mr. name” if the person is a man and “Good morning Mrs. Name” for a woman.
3.5. Recursion
Some problems are recursive in nature. This means that the solution to such problems involves the
repeated application of the solution to its own values until a certain condition is reached.
Algorithms for such problems are known as recursive algorithms.
A recursive algorithm is an algorithm that calls (invokes) itself during its execution. Examples are
the factorial function and the sum function.
Recursion can be defined as the calling of a procedure by itself, creating a new copy of the procedure.
151
Advanced Level Computer Science/ICT
a. Factorial Function
Factorial is defined as:
1! = 1
2! = 2 × 1 = 2
3! = 3 × 2 × 1 = 6
4! = 4 × 3 × 2 × 1 = 24
5! = 5 × 4 × 3 × 2 × 1 = 120
…
�! = � × � − 1 × � − 2 × … × 2 × 1
By studying the above equations closely, we see that the factorial of any number � can be calculated
by multiplying the number by the factorial of the preceding number.
We therefore have:
1! = 1
2! = 2 × 1!
3! = 3 × 2!
4! = 4 × 3!
5! = 5 × 4!
…
�! = � × (� − 1)!
Remark 1! = 1 is known as the base case. Every recursive problem must always have some base
case which can be solved without recursion. For cases that are to be solved recursively, the
recursive call must always make progress towards the base case.
Sum(5) = 1+2+3+4+5
152
Advanced Level Computer Science/ICT
We can see that for any number n, the sumsum(n), is the numbern plus the sum of the previous
numbers.
The sum function can therefore be defined recursively as:
���(1) = 1
���(2) = 2 + ���(1) The base case is � = 1
���(3) = 3 + ���(2) which gives ���(1) = 1
���(4) = 4 + ���(3)
…
���(�) = � + ���(� − 1)
getn
��� 0
if� = 1then
��� 1
else
��� n + ���(� − 1)
return sum
Get �
���(0) = 0 ��� 0
���(1) = 1 if� = 0then
��� 0
���(�) = ���(� − 1) + ���(� − 2) else
if� = 1then
��� = 1
���(0) and ���(1) are the base cases. else
��� fib(� − 1) + ���(� − 2)
return fib
153
Advanced Level Computer Science/ICT
a. Bubble Sort
Bubble sort algorithm arranges items in order as follows:
- First, examine the first two items in the list. If they are in order, leave them alone; if not,
interchange them.
- Do the same with the second and third items, then with the third and fourth items, until you
have reached the last two. At this point you are guaranteed that the item that should come last
in the list has indeed “bubbled” up to that position.
- Now repeat the whole process for the first (n-1) items in the list, then for (n-2)and so on until
the list is sorted.
b. Selection Sort
To perform an insertion sort, examine every item in the list except the first. Whenever you find an
item that should come before the item that immediately precedes it, pick up the item, shift its
neighbor on the left (predecessor) one step to the right, and see whether you can put the current
item in the space thus vacated. If not, shift that item to the right and try again.
c. Insertion Sort
a. Sequential Search
Sequential search is a simple technique for searching an item in a list by comparing each element
with the element searched for, beginning with the first element until the element is found.
b. Binary Search
4. Programming
Programming is the activity of writing computer programs. A computer program is a set of
instructions that will be followed by a computer to perform a computation. These instructions are
made up of statements written in some languages specially designed for this purpose. These
languages are called programming languages.
In other words, a program is an algorithm expressed in a programming language.
154
Advanced Level Computer Science/ICT
a. Machine Language
Machine language is the computer’s language. It is the language the computer understands. Machine
language instructions are written in binary (a series of 0s and 1s), and are directly executable by the
computer. Each machine language statement corresponds to one machine action. Machine language
is the first generation of programming languages. For example a short (3 instruction) program
might look like this:
b. Assembly Language
Assembly language is a low-level language consisting of mnemonic codes and symbolic addresses
corresponding to machine language instructions. Assembly language is the second generation of
programming languages. For example:
155
Advanced Level Computer Science/ICT
4.2. LanguageTranslators
To run a program on a computer, the program needs to be translated into the machine language of
the computer on which it will run. A language translator is a computer program that translates
program instructions from one programming language to another without loss of original meaning.
There are three types of language translators: compiler, interpreter and assembler.
4.2.1. Assembler
An assembler translates assembly language into machine language. The process is called assembling.
156
Advanced Level Computer Science/ICT
Program assembling
4.2.2. Compiler
A compiler translates the entire high-level program into a machine language program. The high-
level language program is called source program or source code and the generated machine
language program is called object program or object code. This process is called compilation. Some
compilers convert high-level language into assembly language, then an assembler is used to create
the finished object code.
Program compilation
Advantages of a Compiler
o Fast in execution
o The object code produced by a compiler can be distributed or executed without having to
have the compiler present.
o The object program can be used whenever required without the need of recompilation.
Disadvantages of a Compiler
o Debugging a program is much harder. Therefore not so good at finding errors
o When an error is found, the whole program has to be re-compiled
4.2.3. Interpreter
An interpreter is a computer program that translates and executes instructions written in a high-
level language into machine language instructions one line at a time. The interpreter translates an
instruction and allows it to be executed before translating the next line. If a program performs a
section code 1000 times, then the section is translated into machine code 1000 times since each line
is interpreted and then executed.
Program interpretation
157
Advanced Level Computer Science/ICT
Advantages of an Interpreter
o It is good at locating errors in programs
o Debugging is easier since the interpreter stops when it encounters an error.
o If an error is corrected, there is no need to retranslate the whole program
Disadvantages of an Interpreter
o It is slow as interpretation and execution is done line by line.
o Translation has to be done every time the program is to be executed since no object code is
produced.
o For the program to run, the interpreter must be present
4.3.4. Debugging
An error in a computer program is known as a bug. Debugging is the process of detecting and
removing bugs. Syntax errors and semantic errors are bugs. A debugger is the software tool used for
this purpose.
158
Advanced Level Computer Science/ICT
a computation. High level languages can be classified under four different paradigms: procedural,
functional, object-oriented and declarative paradigms.
a. Class
A class is a description of an object or a real life concept. Classes are templates for creating objects,
providing initial values for instance variables (attributes) and the bodies for methods. All objects
generated from the same class share the same methods, but contain separate copies of the instance
variables. New objects can be created from a class by applying the new operator to the name of the
class.
ClassPerson {
private:
charname[20];
charsex;
datebirthdate;
public:
updateInfo();
returnAge();
};
The name of the class is person. It has four instance variables (attributes)name,sexand age, and
three methods: updateInfo(),and returnAge(). These methods act on the instance variables when
invoked.
159
Advanced Level Computer Science/ICT
b. Object
An object is an instance of a class. An object consists of a collection of attributes, representing the
state of the object, and a collection of methods, representing the behavior that the object is capable
of performing. Attributes are sometimes referred to as the fields of an object. The methods are
routines that are capable of accessing and manipulating the values of the attributes of the object.
Objects interact with each other by sending messages. When a message is sent to an object, the
corresponding method of the object is executed.
c. Abstraction
d. Encapsulation
Encapsulationis the process of combining together the attributes and methods of a class into a single
abstract data type with a public interface and a private implementation. The goal of encapsulation is
to protect the implementation from the users of the object. It ensures that all access to the internal
representation of the object pass through the class methods, which act as an "interface" to the object.
This is done by making properties and methods “private.”
e. Inheritance
Inheritance is the derivation of one class from another so that the attributes and methods of the
derived class are part of the definition of the initial class. The initial class is often called the base
class, parent class or superclass while thederived class is often referred to as the child class or sub-
class. The subclass usually contains all the attributes and methods of the superclass plus some of its
own.
For example: the class Student inheriting from the class person will have all the attributes and
methods of Person plus the following:
Person Person
Student Teacher
160
Advanced Level Computer Science/ICT
There are two types of Inheritance: multiple inheritance and multilevel inheritance.
Multiple inheritance iswhen a derived class inherits features from more than one superclass.
It is illustrated as follows:
Derived class
Multi-level inheritance is when a class inherits from a class which is itself inherited from
another class. It is illustrated as follows:
Base class
Derived class 1
Derived class 2
f. Polymorphism:
Polymorphism is the use of different methods, each with the same name, which are associated with
different object types. In other words, it is the ability for different objects to respond to the same
message in different, class-specific ways. Polymorphic methods are used which have one name but
different implementations for different classes.
Assume you have a “shape” superclass. This class has a method called “area” which returns the area
of the shape. Polymorphism allows you to make subclasses like “circle,” “square,” and “triangle”
which inherit the “area” method, but each subclass would return the correct value even though they
have different formulas to calculate their areas.
161
Advanced Level Computer Science/ICT
4.5. C Programming
C is a high-level programming language developed by Dennis Ritchie and Brian Kernighan at Bell
Labs in the mid-1970s. Although originally designed as a systems programming language, C has
proved to be a powerful and flexible language that can be used for a variety of applications, from
business programs to engineering.
The first major program written in C was the UNIX operating system, and for many years C was
considered to be inextricably linked with UNIX. Now, however, C is an important language
independent of UNIX.
C is a particularly popular language for personal computer programmers because it is relatively
small - it requires less memory than other languages.
162
Advanced Level Computer Science/ICT
Declaration of functions
Function main()
Definition of functions
For example:
#include <stdio.h>
#include <math.h>
The file “stdio.h” contains standard input and output functions that are used to get input (scanf) and
print output (printf). The file “math.h” contains math functions used for mathematic calculations.
Where
o Identifier specifies the macro name to which a value will be assigned
o Expression specifies the value that is assigned to the identifier. It may be a constant value, a
string or an arithmetic expression.
For example:
#define Pi 3.14
#define CityLimbe
b. Declaration of Variables
163
Advanced Level Computer Science/ICT
A variable is a memory location reserved to contain a value that may change during the execution of
the program. Variables are used for storing input data or values generated as result of processing.
Variables are characterized by their name, type and scope.
Variable Names
A variable’s name or identifier in C can be anything from a single letter to a word. However, it must
begin with a letter or the underscore character but the other characters in the name can be chosen
from the following sets:
a ..z (any letter from a to z)
A .. Z (any letter from A to Z)
0 .. 9 (any digit from 0 to 9)
_ (the underscore character)
Examples of valid variable identifiers are: x, total, area_of_circle, x1, _a and aX.
Remark! C is case sensitive, so the identifiers sum and SUM are different. Same for total and Total.
All key words must be in lower case.
Variable Types
Every variable has a type. The type of the variable specifies what sort of data will be stored in it. The
type of a variable is specified during its declaration. To declare a variable in C, one writes the type
followed by the variable name or identifier.
The general syntax for declaring a variable is:
For example:
int age;
float area;
int sum = 0;
inti,j=2;
o int specifies that the variables age and sum are integers while float specifies that the variable
area is a floating point (real or decimal) number.
o int sum=0 indicates that variables can be assigned values when they are declared. This is
called initialization. Therefore, one can initialize a variable at the time of declaration.
o i and j are integers with j initialized at 2.
164
Advanced Level Computer Science/ICT
o It provides the compiler with a list of the variables in a convenient place so that it can cross
check names and types for any errors.
Type Description
1. Char a single ASCII character
C fun!
int standard integers (usually 32 The bank said they couldn’t FLOAT our loan because we were LON
2. debt and SHORT of funds. Our application was UNSIGNED, so the w
bits)
deal was VOID. Can you believe it? The bank rejected us in C-speak!
3. long int (long) long integers
Float standard floating point or
4.
real numbers
long float long floating point numbers Scope of a Variable
5.
(double) The scope of a variable describes where in
6. unsigned int positive short integers the program the variable can be legally
unsigned float positive standard floating used. Based on its scope, a variable can be
7.
point numbers global or local.
8. unsigned long positive long integers A global variable is a variable that can be
unsigned double positive long floating point recognized anywhere in the program.
9. Global variables are declared before the
numbers
function main().
A local variable is a variable that has meaning only within a particular function or other program
unit. Local variables can be declared anywhere following the opening brace ({) of a block. The name
of a local variable can be used in another block elsewhere in the program, where it will refer to an
entirely different variable.
The keyword “int” is used before the main() function to indicate the type of the value that is
returned by the main() function. By definition, a function may accept no, one or more inputs
and returns no or a single value. 'int' means that the program will return an integer value after
its execution. The word “void” can be used in the place of “int” to indicate that the program will
not return any value.
165
Advanced Level Computer Science/ICT
It is good practice to always return a value because the operating system uses the return value
to determine whether the program has been executed successfully or not.
The body of the main() function must be enclosed in braces (or curly brackets { }). These
braces are called delimiters. The left brace indicates the start of the body of the function
whereas the matching right brace indicates the end of the body of the function. Braces are also
used to indicate the beginning and ending of block (compound) statements.
Remark! The use of 'void' or 'int' before the function main() is optional. If it is not specified, the
compiler assumes it is int.
The body of the function main() is made up of program statements which represent
instructions to be executed by the computer. An instruction may be an input/output
statement, an arithmetic statement, a control statement, a simple assignment statement or
any other statement.
Example:
scanf("%d", &x);
This statement reads a decimal integer from the keyboard and stores the value in the memory
address of the variable x.
In the statement,
%d is a conversion specifier and specifies that the variable to be readis of type integer. Other
conversion specifiers used in C are %f for floating point numbers, %c for characters and %s for
strings.
166
Advanced Level Computer Science/ICT
&gives the address of something in memory. That is, it generates a pointer to the object.The
arguments to scanf must be pointers (addresses), hence the need for &.
Example:
printf("The radius is %f cm",x);
in the statement,
“The radius is %f cm” is the control string. The text in between the double quotes will be
displayed except the conversion specifier %f.
x is the variable to be printed. The value of x will be printed where the conversion specifier is
placed in the control string.
Many conversion specifications can be used in a control string. In this case, the programmer has to
ensure that both the number of conversion specifications and the number of variables to be printed
are the same and, of the correct type specified.
Example:
printf(“The sum of %d and %d is %d”, x, y, x+y).
If x=2 and y=3, then what will be displayed on the screen is: The sum of 2 and 3 is 5
Examples:
scanf(“%s”, &Name);
printf(“Name: %s”, Name);
167
Advanced Level Computer Science/ICT
scanf("%d %d",&x,&y);
printf("The sum of %d and %d = %d",x,y,z);
d. Character Input/Output
getchar and putchar are used for the input and output of single characters respectively.
getchar() returns an int which is either EOF (indicating end-of-file) or the next character in the
standard input stream
putchar(c) puts the character c on the standard output stream
#include<stdio.h>
main()
{ charch;
ch=getchar();
printf(“%c”,ch);
}
a. Arithmetic Operators
Arithmetic operators are used for arithmetic calculations.
Operator Description
1. + Addition
2. − Subtraction
3. ∗ Multiplication
4. / Division
5. % Remainder after division(modulo
arithmetic)
b. Relational Operators
Relational operators are used for comparisons. Expressions that use these operators produce a true
or false value when they are evaluated.
168
Advanced Level Computer Science/ICT
c. Logical Operators
Logical operators are used to combine logical values.
Remark! Bitwise operators allow manipulation of the actual bits held in each byte of a variable.
Other bitwise operators are:
Right shift (>>) – binary division by 2
E.g. if � == 0010111 then �>>= 0001011.
Also, �>>2 = 0000101
Left shift (<<) – binary multiplication by 2
If � == 0010111 then �<<= 0010110.
Also, �<< 2 = 1011100
One’s complement (~)
If � == 0010111 then � ~ = 1101000
d. Assignment Operators
Assignment is the process of storing a value in a variable. The assignment operator is the equal sign
(=).
For example:
�� = 3.14
s�� = ��� + 1
169
Advanced Level Computer Science/ICT
The variable ��is assigned the value 3.14 and the variable sum is incremented by 1.
++ Increment �++ ≡ � = � + 1
-- Decrement �-- ≡ � = � − 1
These operators can be prefix or postfix. With the prefix form the variable is changed before the
value of the expression in which it appears is evaluated, and with the postfix form the variable is
modified afterwards.
� = 3; � = 3;
� = �++ + 6; /* a = 9, b = 4 */ � = ++� + 6; /* a = 10, b = 4 */
170
Advanced Level Computer Science/ICT
a. The IFStatement
The IFstatement is a decision-making statement that is used to evaluate an expression and then take
one of two possible actions depending on the validity of the expression.The IF statement has two
forms.
Syntax:if(expression)
statement(s);
and
if (condition)
{
statement(s);
}
else
{
statement(s)
}
In the first form, if the expression specified in the if statement evaluates to true, the statements
inside the if-block are executed and then the control gets transferred to the statement immediately
after the if-block.
In the second form, the else part is required only if a certain sequence of instructions needs to be
executed if the expression evaluates to false.
scanf(“%d”,&b);
if (b>0)
printf(“Number %d is positive”,b);
else
printf(“Number %d is negative”,b);
Sometimes we may want to evaluate more than one thing in an expression. This can be done in C by
using the logic operators AND and OR.
171
Advanced Level Computer Science/ICT
For example:
if (a==0 || b==1)
This expression is TRUE if a is 0 OR b is 1. It is also true if� = 0and� = 1.
if (a == 1 && b == 2)
This expression is TRUE if � is 0 AND� is 1. If one is NOT TRUE, the whole expression is evaluated to
FALSE. In other words, � must equal 0 and � equal 2, for the expression to be TRUE.
C Fun!
Shakespeare must have been disappointed to learnthat, whatever
the value of a variable tobe, the result of the question tobe || !tobe,
isalwaystrue. Fortunately, thisis not a question of life or death!
b. Nested IF
It is also possible to embed or to nest IF statements one within the other. Nesting is useful in
situations where one of several different courses of action need to be selected.
Example:
#include<stdio.h>
int main()
{ int a, b;
scanf(“%d %d ”, &a,&b);
if(a>b)
{
printf("%d is greater.", a);
}
else
if(a==b)
{
printf("%d and %d are the same: ", a,b);
}
else
{
printf("%d is greater.", b);
}
return 0;
}
c. SWITCH Statement
172
Advanced Level Computer Science/ICT
A switch statement is used for multiple way selections that will branch into different code segments
based on the value of a variable.
Syntax:switch(variable)
{
casevalue1 : code segment1; break;
casevalue2 :code segment2; break;
…
casevalueN : code segment N; break;
default: statement(s);
}
If the value of the variable equals ‘value1’, code segment1 is executed. Otherwise, if it equals value2,
code segment2 is executed and so on.
The statement break is used after every case in order to prevent execution from continuing into the
code segment of the next case without even checking its value.
For example, supposing a switch statement has five cases and the value of the third case matches
the value of expression. If no break statement were present at the end of the third case, all the cases
after case 3 would also get executed along with case 3. If break is present only the required case is
selected and executed; after which the control gets transferred to the next statement immediately
after the switch statement. There is no break after default because after the default case the control
will either way get transferred to the next statement immediately after switch.
#include<stdio.h>
int main()
{ int a, b; char op;
printf("Enter two integers: ");
scanf(“%d %d”, &a, &b);
printf("Enter an operator: ");
scanf("%c", &op);
switch(op)
{
case+: printf("%d + %d = %d ", a, b, a+b); break;
case-: printf("("%d - %d = %d ", a, b, a-b); break;
case*: printf("("%d * %d = %d ", a, b, a*b); break;
case/: printf("%d / %d = %f ", a, b, a/b "); break;
default: printf("Error!");
}
return 0;
}
173
Advanced Level Computer Science/ICT
Remark! If you need to select among a large group of values, a switch statement will run much
faster than a set of nested IFs.
The switch differs from the IF in that switch can only test for equality, whereas IF can evaluate any
type of Boolean expression.
d. WHILE Statement
The While statement or while loop is an iteration statement. Iteration statements are used to
execute a particular set of instructions repeatedly until a particular condition is met or for a fixed
number of iterations.
Syntax:while (condition)
{
statements;
}
The statement or statements are only executed if the expression is true (non-zero). After every
execution of the statements, the expression is evaluated again and the process repeats if it is true.
Example:
int i=1;
while(i<=10)
{
printf(“%d”, i);
i++;
}
This code will loop 10 times writing the numbers 1 to 10.
Example: A program that counts the number of blank spaces in a line of text.
#include <stdio.h>
int main()
{ charch; short count = 0;
printf("Type in a line of text\n");
while((ch = getchar()) != '\n')
{
if(ch == ' ')
count++;
}
printf("Number of spaces = %d\n",count);
return 0;
}
174
Advanced Level Computer Science/ICT
Syntax:do {
statements to be executed;
} while(expression);
Remark!
Pay attention to the semicolon which ends the do-while statement.
The difference between while and do-while is that the while loop is an entry-controlled loop -
it tests the condition at the beginning of the loop and will not execute even once if the
condition is false, whereas the do-while loop is an exit-controlled loop - it tests the condition at
the end of the loop after completing the first iteration.
#include<stdio.h>
int main()
{ int n, a,sum=0;
printf("Enter a number:");
scanf("%d", &n);
do{
a =n%10;
sum=sum+a;
n=n/10;
} while(n>0);
printf("Sum of the digits = %d",sum);
return 0;
}
A practical use of the do-while loop is in an interactive menu-driven program where the menu is
presented at least once and then depending upon the choice of the user, the menu is displayed again
or the session is terminated. Consider the same example that we saw in switch-case. Without using
an iteration statement like do-while, the user can choose any option from the menu only once.
Moreover, if a wrong choice is entered by mistake the user doesn’t have the option of entering his
choice again. Both these faults can be corrected by using the do-while loop.
f. FOR Statement
The FOR statement or the FOR loop repeatedly executes a set of instructions that comprise the body
of the loop until a particular condition is satisfied.
175
Advanced Level Computer Science/ICT
The initialization expression initializes the looping index which controls the looping action.
The initialization expression is executed only once, when the loop begins.
The termination expression represents a condition that must be true for the loop to continue
execution.
The increment/decrement expression is executed after very iteration to update the value of
the looping index.
#include <stdio.h>
int main()
{ int a, b, i, prod=0;
scanf(“%d”,&a);
scanf(“%d”,&b);
for (i=1;i<=b;i++)
prod=prod+a;
printf(“%d”,prod);
return 0;
}
4.5.5. Arrays
An array isa collection of data items of the same type that are given a single name (identifier) and
distinguished by numbers (subscripts).In simple terms, an array is a list of elements of the same
type. When an array is created (declared), its size (dimension) and the type of its elements are
specified. Arrays can be one dimensional or multidimensional.
a. One-Dimensional Arrays
One-dimensional arrays are declared using a single index (subscript).
For example:
int A[10], char Name[10], int vect[20]
int A[10] creates an array called “A” of 10 integers. The elements of array A are referenced as:
A[0], A[1], [2], … A[8], A[9]
176
Advanced Level Computer Science/ICT
Where A[0] is the first element in the array, A[1] the second element, A[2] the third element and A[9]
the last element.
Values can be assigned to the array as if each element were a separate variable.
A[0] =3; A[1] =1; A[2] =0; … A[9] =-5
b. Two-Dimensional Arrays
Two dimensional arrays are declared using two indices (subscripts).
For example:
int A[3][2], int B[5][3], int M[3][4]
int M[3][4] declares a 3x4 array where 3 is the number of rows and 4 the number of columns. The
elements of the array M can be visually represented as a table as follows:
177
Advanced Level Computer Science/ICT
The elements of a 2-dimensional array can be assigned using nested loops or as separate variables.
As separate variables
int main( )
{ int i, j, n=3, m=4;
for(i=0; i<n; i++)
for(j=0; j<m; j++)
{
printf(“M[%d][%d] = ”, i, j);
scanf(“%d %d”,&M[i][j]);
}
return 0;
}
The elements of a 2-dimensional array can be displayed using nested loops or as separate variables.
Using nested loops, we have
int main( )
{ int i, j, n=3, m=4;
for(i=0; i<n; i++)
for(j=0; j<m; j++)
printf(“M[%d] [%d]=%d ”, i, j, M[i][j]);
return 0;
}
a. Function Declaration
A function declaration (also called function prototype) is simply a statement which specifies the
function’s type, name and parameter or argument list.Function names follow the same rules as
variable names. The general syntax for declaring a function is:
178
Advanced Level Computer Science/ICT
Remark! Parameter names are optional in a function prototype, so for the above prototypes we
could have written:
int square(int)
int power(int, int)
b. Function Definition
Function definition consists of writing the actual statements of the function. A function definition
has the form:
For example:
FloatareaCircle(int r) int square(int r)
{ float area; { intsqr;
area = 3.14*r*r; sqr=r*r;
return (area); return (sqr);
} }
A function that has been defined can be called within the function main()or within any other
function.
For example:
#include<stdio.h> #include<stdio.h>
Float areaCircle(int) //prototype int square(int) //prototype
Remarks!
If the type of a function is not specified, C will always assume that the function is of typeint.
Notice that the function areaCircle was declared in the variables section of the function main().
Thisis because, if a function whose type is not int is not declared in the variables section of the
function in which it is called, compilation errors will occur.
The names used by a function for its parameters are local to the function, and are not visible to
any other function: other routines can use the same names without conflict. This is also true of
the variables declared within the function.
When a function is called, parameters are passed to the function as inputs. In the above
examples, ��� and � are passed to the functions areaCircle and square respectively.
These parameters which replace the formal parameters when a function is called are passed
either by value or by reference. A parameter is passed by value when the value of the
parameter is calculated and this is passed into the function. A parameter is passed by reference
by using pointers. Pointers are addresses.
Introduction
There may be several different methods for solving a particular problem. How can one decide which
method is the best in a certain situation? How would one define "best" – is it the fastest method or
the one that takes up the least amount of memory space?
Understanding the relative efficiencies of algorithms designed to do the same task is very important
in every area of computing.
1. Computational Complexity
Complexity theory is the mathematical study of the time and amount of memory needed to perform
a computation. The goal of computational complexity is to classify algorithms according to their
performances.
The efficiency of an algorithm can be measured in terms of:
The execution time (time complexity)
The amount of memory required (space complexity).
180
Advanced Level Computer Science/ICT
Statements 1, 2, and 3 are each executed once. Statements 5, 6, and 7 are each executed n times.
Statement 4 (which controls the loop) is executed n + 1 times (one additional check is required), and
statement 8 is executed once. The running time T(n) of this algorithm is given as follows:
Number of
�(�) = 1 + 1 + 1 + � + 1 + � + � + � + 1 = 4� + 5
Statement times
executed
1.1.1. Big-O Notation
1 1
Big-O notation also called Landau's symbol, is a symbolism used to describe
2 1
the asymptotic behavior of functions. Basically, it assesses by what factor
3 1
execution time increases when the size of the input is increased. The letter O is
4 n+1
used because the rate of growth of a function is also called its order of growth.
5 n
For example, let’s suppose that the execution time for an algorithm of input
6 n
size � is given by:
7 n
� � = 4�2 − 2� + 2 8 1
Ignoring constants as they depend on the particular hardware the program is running on, and
slower growing terms, we could say "T(n) grows at the order of �2 " and write:
�(�) = �(�2 )
This simply means that if the input size (n) doubles, the algorithm takes four times longer to execute
and the order of growth is said to be quadratic.
Some programs perform the same number of operations every time they are executed while others
may perform different numbers of operations, depending onthe value of a parameter.
181
Advanced Level Computer Science/ICT
Suppose a computer is going to process �items of input. The time complexity of the calculation may
be any of the following:
Remark! Big-O expressions do not have constants or low-order terms. This is because, when � gets
large enough, constants and low-order terms don't matter.
A constant-time algorithm will be faster than a linear-time algorithm, which will be faster than a
quadratic-time algorithm.
182
Advanced Level Computer Science/ICT
Best Case: K is the first item that we check, so only one comparison.
Worst Case: K is not in the array, then we must search every item (� comparisons)
Average Case:
(a) Place the following algorithms in order of efficiency, the most efficient first.
1.2. SpaceComplexity
Space complexity is essentially the amount of memory (number of cells) which a program needs to
execute. A good algorithm keeps this number as small as possible.
2. Computability
Computability deals with whether a problem can be solved at all, regardless of the resources
required.
2.1. TuringMachines
A Turing machine (TM) is an imaginary machine conceived by Alan Turing in the 1930s to help
identify the kinds of problems that are potentially solvable by machines. It consists of a read/write
head and an infinite string of paper tape made up of cells where each cell can hold a symbol from the
tape alphabet.
The head scans at a cell on the tape and can read, erase, and write a symbol on the cell. In each move,
the head can move to the right cell or to the left cell or stay in the same cell.
183
Advanced Level Computer Science/ICT
A TM begins computation at state s0. At each computational step, it reads the present tape symbol,
changes its internal state, optionally writes another symbol onto tape, and moves one cell to the left
or right in the tape.
The TM halts computation (and accepts the input string) when it reaches one of the halt states in H.
3. Computable Functions
A function is computable if it can be computed by a Turing machine.
4. Decidability
5. The Halting Problem
184
Advanced Level Computer Science/ICT
Introduction
Most computer-based information systems are conceived, designed, and implemented using some
form of systematic development process called software development process. In this process, end
users and system analysts design systems based on an analysis of the information requirements of
the information system to be built. The software development process is also called system
development life cycle.
Development
and Testing
1.1. SystemStudy
System study is a brief investigationof the system under consideration that gives a clear picture of
what actually it is. During this phase, the system is evaluated and deficiencies are identified. This
can be done by interviewing users of the system and consulting with support personnel. Main
activities at this stage are:
Determining whether a business problem or opportunity exists. i.e. identifying problems and
opportunities.
185
Advanced Level Computer Science/ICT
1.2. SystemAnalysis
Systems analysis is an in-depth study of end user information needs which produces functional
requirements that are used as the basis for the design of a new information system. System analysis
describes what a system should do to meet the information needs of users. It involves:
186
Advanced Level Computer Science/ICT
The outcome of a feasibility analysis is a feasibility report which is presented to the user
management for approval. It may be accepted or accepted with modifications or rejected.
1.3. SystemDesign
Systems design consists of design activities, which produce systems specifications satisfying the
functional requirements developed in the systems analysis stage. While system analysis specifies
what is to be done by the new system, system design describes how the system will accomplish
what is to be done.
System design focuses on three main activities: user interface design, data design and process
design.
1.3.2. DataDesign
Data design focuses on the design of the structure of data and files to be used by the proposed (new)
system. It provides detailed descriptions of:
o Attributes (characteristics) of the entities about which the proposed system needs to
maintain information.
o Relationships between these entities (E-R diagrams, data flow diagrams)
187
Advanced Level Computer Science/ICT
o Specific data elements (databases, files, records, etc.) that need to be maintained for each
entity.
o Data dictionary
o Integrity rules (data validation and verification) that govern how each data element is
specified and used in the system.
1.3.3. ProcessDesign
Process design focuses on the design of software resources, that is, computer programs and of
procedures needed by the proposed system. It concentrates on developing detailed specifications
for the program modules that will have to be purchased as software packages or developed by
custom programming. Process design produces:
o Detailed specification of algorithms (pseudo-codes, flow charts, etc.)
o Detailed specifications of the procedures needed to meet the user interface and data design
specifications.
o Detailed specification of the database schema (E-R diagram, object diagrams)
The design stage is very important because it is the place where quality is fostered in software
engineering. Design provides us with representations of software that can be assessed for quality.
Design is the only way that we can accurately translate a customer's requirements into a finished
software product or system.
1.4.2. Prototyping
Prototyping is the rapid development and testing of a working model of a product in an interactive
and iterative process involving both systems analysts and end users. This working model or
prototype, is a partially developed product that enables customers and developers to examine some
aspects of the proposed product and decide if it is suitable for a finished product.
Various types of prototyping exist.
a. Throw-away Prototyping
In throw-away prototyping, the prototype is discarded once the actual requirements have been
understood and the final system is developed with a much clear understanding of user
requirements.
188
Advanced Level Computer Science/ICT
b. Evolutionary Prototyping
In evolutionary prototyping, a functional prototype with minimal functionality is built in the
beginning and is refined over time, as requirements are better understood.
c. Incremental Prototyping
In incremental prototyping, functional prototypes of the various subsystems are built and then
integrated to form a complete system. In other words, the product is built as separate prototypes
which are later merged into a final product.
1.4.3. Testing
Testing is the process of executing a program with the intent of finding an error. During testing, trial
runs are done to check for errors and whether or not the new system meets the users' needs. Once
source code has been generated, the software must be tested to uncover and correct as many errors
as possible before delivery.
There are three sets of data that can be used to test the system: normal data and abnormal data.
o Normal data is data which the system will accept.
o Abnormal (erroneous) data is invalid data which the system will reject.
o Extreme data are data values that are chosen at the absolute limits of the normal range. This
is to ensure that all normal values will be accepted and processed correctly.
Using these test data, the following test runs can be carried out:
a. Unit Testing
The individual units or modules are tested separately with prepared test data so that any errors can
be corrected.
b. Integration Testing
The complete system is tested after the individual units have been tested and put together. This
tests that separately developed modules/units work together as planned without error.
c. System Testing
The integrated system is tested to evaluate the system's compliance with specified requirements.
d. Black-Box Testing
Black-box testing is a test that relies on the input/output behavior of the system, without any
assumptions to what is happening within the system. It examines some fundamental aspects of a
system with little regard for the internal logical structure of the system. Black-box tests are used to
demonstrate that system functions are operational, that input is properly accepted and output is
correctly produced, while at the same time searching for errors in each function.
189
Advanced Level Computer Science/ICT
1.4.4. Documentation
The job of the programmer does not end with the code or software instructions. The organization or
users need to know how to get the best out of the system. This is done through documentation.
System documentation ensures continuity of the system.
There are two types of documentation; user documentation and technical documentation.
a. User Documentation
User documentation is a complete description of the system from the user’s point of view detailing
how to use or operate the system. It could be a paper-based user manual or help incorporated into
the software that can be accessed when the software is installed. User documentation always covers
the following:
o A guide that describes what the system is supposed to do in non-technical terms
o Instructions for installing and running the program
o Definition for hardware and Operating System requirements
o The format of the output data
o Explanation of common error messages and how to recover from them
o Description of how to make backups against accidental data loss
b. Technical Documentation
Technical documentation is a description from the designer’s point of view. Technical
documentation often contains:
o Detail functioning of the software showing algorithms, formulae, source codes etc.
o Description of data structures
o Test plans and testing procedures
o User interface and reports
o Location and version of the software
1.5. Implementation
Implementation is the conversion from the use of the present (old) system to the operation of the
new system. It involves:
Installation of new system
Loading of data into new system
Education and training of users of the system
190
Advanced Level Computer Science/ICT
a. Direct cutover
The old system is completely replaced by the new one. Its disadvantage is that, if the new system
fails, there is no back-up system, so data can be lost.
b. Pilot run
The new system is installed in one part of the business or organization. This allows the new system
to be fully developed and tested. Once the pilot system is running successfully, the new system is
introduced to all of the business/organization.
o Its advantages are that, if something goes wrong with the new system, only a small part of the
organization is affected, and the staffs that were part of the pilot scheme can help train other
staff.
o As a disadvantage, there is no back-up system for the office/department doing the pilot, if
things go wrong.
c. Parallel run
The old and new systems are operated alongside each other (in parallel) until new system is proven
capable.
o It is advantageous in that, if the new system fails, the old system will act as a back-up. Also, the
outputs from the old and new systems can be compared to check that the new system is
running correctly.
o Its disadvantage is that, entering data into two systems, and running two systems together,
takes a lot of extra time and effort.
d. Phased implementation
The new system is installed in phases (stages or steps) gradually replacing parts of the old system
until eventually, the new system takes over.
o Its advantages are that, it allows users to gradually get used to the new system, and training of
staff can be done in stages.
o Its disadvantage is that, if a part of the new system fails, there is no back-up system, so data
can be lost
1.6. Maintenance
Maintenance is the general process of changing a system after delivery to correct faults, improve
performance or adapt the system to a changing environment or business requirements.
Maintenance is necessary to eliminate errors in the system during its working life and to tune the
system to any variations in its working environment.
Maintenance can be adaptive, preventive, corrective or perfective.
a. Adaptive Maintenance
191
Advanced Level Computer Science/ICT
b. Preventive Maintenance
Preventive maintenance aims in retaining the system’s capabilities before the occurrence of any
problem (e.g. system failure). It locates weaknesses in the system and provides repairs in order to
avoid any eventual breakdown of the system.
c. Corrective Maintenance
Corrective maintenance aims in restoring a defective system to a required state. This implies that
repairs are made after a breakdown of the system.
d. Perfective Maintenance
Perfective maintenance refers to enhancements to the product in order to either add new
capabilities or modify existing functions.
2. SDLC Models
There are various SDLC models defined and designed which are followed during software
development processes. These models are also referred to as "Software Development Process
Models". Each model follows a series of steps unique to its type, in order to ensure success in the
process of software development.
Analysis
Design
Implementation
Testing
Maintenance
Waterfall Model
Advantages
o Simple and easy to use.
192
Advanced Level Computer Science/ICT
o Easy to manage due to the rigidity of the model – each phase has specific deliverables and a
review process.
o Phases are processed and completed one at a time.
o Works well for smaller projects where requirements are very well understood.
Disadvantages
o Adjusting scope during the life cycle can kill a project
o No working software is produced until late during the life cycle.
o High amounts of risk and uncertainty.
o Poor model for complex and object-oriented projects.
Testing
V-Shape Model
V-shape model is an extension of the waterfall model and is based on association of a testing phase
for each corresponding development stage. This means that for every single phase in the
development cycle there is a directly associated testing phase. This is a highly disciplined model and
next phase starts only after completion of the previous phase.
Advantages
o Simple and easy to use.
o Each phase has specific deliverables.
o Higher chance of success over the waterfall model due to the development of test plans early
on during the life cycle.
o Works well for small projects where requirements are easily understood.
193
Advanced Level Computer Science/ICT
Disadvantages
o Very rigid, like the waterfall model.
o Little flexibility and adjusting scope is difficult and expensive.
o Software is developed during the implementation phase, so no early prototypes of the
software are produced.
o Model doesn’t provide a clear path for problems found during testing phases.
Advantages
o High amount of risk analysis
o Good for large and mission-critical projects.
o Software is produced early in the software life cycle.
Disadvantages
o Can be a costly model to use.
o Risk analysis requires highly specific expertise.
o Project’s success is highly dependent on the risk analysis phase.
o Doesn’t work well for smaller projects.
3. Software Design
Software design is the process of defining the architecture, components, modules, interfaces, and
data for a software to satisfy specified requirements. It is the activity within the software
development life cycle, where software requirements are analyzed in order to produce a description
of the internal structure and organization of the system that will serve as the basis for its
construction.
A software design must describe the architecture of the system, that is, how the system is
decomposed and organized into components and must describe the interfaces between these
components. It must also describe these components into a level of detail suitable for allowing their
construction.
194
Advanced Level Computer Science/ICT
The problem is broken down into smaller problems called sub-problems, which in turn are broken
into smaller sub-problems, continuing until each sub-problem can be solved in a few steps.
Top-down design leads to modular development. Modular development is the process of developing
software modules individually then combining the modules to form a solution to an overall problem.
Definition: A module is a self-contained entity that results when a problem is divided into sub-
problems; each module corresponds to a sub-problem.
195
Advanced Level Computer Science/ICT
3.3.2. Flowcharts
They are used to show the flow of control and the associated actions to be performed.
S0 S1 S2 S3
196
Advanced Level Computer Science/ICT
3.4. SoftwareReuse
Software reuse is the process of implementing or updating software using existing software assets.
Reusable software assets include more than just codes. Requirements, designs, models, algorithms,
tests, documents, and many other products of the software process can be reused.
Software reuse makes programming easier because you only need to develop the solution to a
problem once; then you can call up that code whenever you need it. Modules developed as part of
one project, can be reused later as parts of other projects, modified if necessary to fit new situations.
Most computer systems are filled with layers of short programming modules that are constantly
reused in different situations.
Software reuse can be horizontal or vertical.
3.4.1. HorizontalReuse
Horizontal reuse refers to software components used across a wide variety of applications. This
type of reuse includes library of components, string manipulation routines, or graphical user
interface functions.
3.4.2. VerticalReuse
Vertical reuse, in another way, deals with the reuse of system functional areas, or domains that can
be shared between systems with similar functionality.
4. Project Management
A project is an endeavor to accomplish a specific objective through a unique set of interrelated tasks
and the effective utilization of resources. A project has a definite start and finish time, well-defined
outcomes or performance goals, and consumes scarce resources such as money, personnel, material,
and equipment.
A project is considered constrained by three functions:
Scope: what it is intended to accomplish. In other words, the customer’s requirements for the
project.
Time allocation: the time schedule for the project.
Cost: the money, budget, and resources for a project.
197
Advanced Level Computer Science/ICT
These three functions are called the Triple Constraint. The relationship between them is
represented using the Project Management Triangle.
Time Cost
Scope
The Project Management Triangle visualizes the fact that time, cost and scope of a project are
interdependent; changing one of them causes changes in the other two. For example, if you want to
shorten a schedule, you can hire more resources which would increase cost, or reduce customer
requirements which would affect quality. This simply means “you can have any two of quick, good
or cheap, but not all three.”
Projects are implemented through project management. Project management is defined as the
application of knowledge, skills, tools and techniques to activities of a project for the achievement of
the project’s objectives/requirements. Project management ensures that an acceptable system is
developed within time and budget.
198
Advanced Level Computer Science/ICT
Critical path:a sequence of dependent tasks that have the largest sum of most likely durations.
The critical path determines the earliest possible completion date of the project.
Critical task: a task found on the critical path. A critical task cannot be delayed without
delaying the entire project schedule.
Work Breakdown Structure: a hierarchical decomposition of the project into phases, activities,
and tasks.
Project management plan (PMP): a document that describes how the project is to beexecuted,
monitored and controlled, which includes creating a project workbreakdown structure,
identifying and planning to mitigate risk, identifyingmanners in which to effectively
communicate with stakeholders and other project team members, and developing a plan to
manage changes.
4.2.1. Initiation
Project initiation determines the main objective of the project and forms a clear understanding
about the necessity and suitability of the project. This stage answers the questions “what?” and
“why?” Common activities at this stage are:
Identification and initial analysis of the business needs.
Determination of the main objective(s).
Resource analysis (people, equipment, financial; needs and availability).
Composition of the project charter.
(Project charter - document issued by the project initiator or sponsor that formally authorizes
the existence of a project, and provides the project manager with the authority to apply
organizational resources to project activities.)
4.2.2. Planning
Project planning involves the project plan development and approval. It determinesan optimal
scheme/algorithm for project execution. This stage answers the question “how?” The main activities
at this stage are:
Needs analysis
Description of the project (including determination of activities and necessary resources)
Composition of project plan
Planning and performing necessary PR-activities.
(PR is the practice of managing the spread of information between an individual or an organization
and the public. Public relations activities include: launchings, media conferences, sales promotions,
open day, product testing, websites, press release, newsletters.)
199
Advanced Level Computer Science/ICT
4.2.3. Execution
Project execution is the phase within which the deliverables are physically constructed and
presented to the customer for acceptance. It integrates people and other resources to carry out the
project management plan for the project. The activities undertaken to construct each deliverable
will vary depending on the type of project being undertaken. Main activities are:
Starting up the execution.
Building the deliverables
Day-to-day management and reporting
4.2.5. Closing
Once all the deliverables have been produced and the customer has accepted the final solution, the
project isready for closure.
Project closureinvolves:
releasing the final deliverables to the customer
handing over project documentation to the business
terminating supplier contracts,
releasing project resources
communicating the closure of the project to all stakeholders
200
Advanced Level Computer Science/ICT
CPM models the events and activities of a project as a network. Activities are depicted as nodes on
the network and events that signify the beginning or ending of activities are depicted as arcs or lines
between the nodes.
a)
b)
Network diagrams
201
Advanced Level Computer Science/ICT
The number marked on each arc (arrow) shows the duration of the task from which the arc
starts.
The critical path can be identified by determining the following four parameters for each activity:
ES – earliest start time: the earliest time at which an activity can begin given that its
predecessor activities must be completed first.
EF – earliest finish time, equal to the earliest start time for the activity plus the time required to
complete the activity.
LF – latest finish time: the latest time at which an activity can be completed without delaying
the project.
LS – latest start time, equal to the latest finish time minus the time required to complete the
activity.
Activities with the same earliest and latest start times (ES=LS) or with same earliest and latest finish
times (EF=LF) define the critical path. This means that these activities have a float time of 0.
202
Advanced Level Computer Science/ICT
C 4 -
D 1 C
E 3 B, D
F 2 A, B, D
G 2 C, F
H 4 G
I 1 C
J 3 E, G
K 5 F, H, I
Exercise 2: Find the critical path for each of the activity networks below.
a.
b.
c.
203
Advanced Level Computer Science/ICT
Remark! CPM was developed for complex but fairly routine projects with minimal uncertainty in
project completion times. For less routine projects there is more uncertainty in the completion
times, and this uncertainty limits the usefulness of the deterministic CPM model. An alternative to
CPM is the PERT (Program Evaluation and Review Technique) project planning model.
Example:
If a project’s expected completion time is � = 246 ���� with its variance σT 2 = 25, then what is the
probability that the project
a) is actually completed within 246 days?
b) is actually completed within 240 days?
c) is actually completed within 256 days
204
Advanced Level Computer Science/ICT
Solution
a) � = 246, � = 246 and σT 2 = 25
246 − 246
� �≥� = =0
25
CPM PERT
1 Uses network,
calculate float or slack,
identify critical path
Same as CPM
and activities, guides
to monitor and
controlling project
2 Requires 3 estimates of
Uses one value of activity time
activity time Calculates standard deviation
and variance of time
3 Used where times can
Used where times cannot be
be estimated with
estimated with confidence.
confidence, familiar
Unfamiliar or new activities
activities
4 Minimizing cost is Meeting time target or
more important estimating percent
205
Advanced Level Computer Science/ICT
4.3.3. GanttChart
A Gantt chart is a horizontal bar graph that helps plan and monitor project development or resource
allocation on a horizontal time scale. It depicts project tasks against a calendar.
A Gantt chart is constructed with a horizontal axis representing the total time span of the project,
broken down into increments (days, weeks, or months) and a vertical axis representing the tasks
that make up the project. Horizontal bars of varying lengths represent the sequences, timing, and
time span for each task. The bar spans may overlap, as, for example, you may conduct research and
choose software during the same time span. As the project progresses, secondary bars, arrowheads,
or darkened bars may be added to indicate completed tasks, or the portions of tasks that have been
completed. A vertical line is used to represent the report date.
A Gantt chart
Exercises!
Exercise 1: A project has been defined to contain the following list of activities along with their
required times for completion.
Time Immediate
Activi
Activity (weeks Predecesso
ty No.
) rs
1 Collect 3
requirements
2 Analyze 2 1
processes
3 Analyze data 2 2
4 Design 6 2
processes
5 Design data 3 3
6 Design screens 2 3,4
206
Advanced Level Computer Science/ICT
Exercise 2: At 4:30 pm one day CRTV news team hears of a Government Minister resigning. They
wish to prepare an item on the event for that evening’s 6 o’clock news. The table below list the
jobs needed to prepare this news item, the time each job takes and the constraints on when the job
can commence.
Time
Job Constraints
needed
A - Interview
the resigning 15 mins. Starts at 4:30 pm
minister
B - Film the
20 mins. None
ministry
C - Get reactions Cannot start until A
25 mins.
from regions and B are completed
D - Review
Cannot start until B is
possible 40 mins
completed
replacements
E- Review the Cannot start until A is
25 mins
minister’s career completed
Cannot start until E
F- Prepare film
20 mins. and
for archives
C are completed
Cannot start until A, B,
G- Edit 20 mins. C, D, E and F are
completed
a. Construct an activity network for this problem and by finding the critical path in your network,
show that the news item can be ready before 6 pm that day.
b. Construct the corresponding Gantt chart for this project
207
Advanced Level Computer Science/ICT
References
[1] D. Kahn, “The Codebreakers, Macmillan Publishing Company, 1976”.
[2] A. Menezes, P. van Oorschot, and S. Vanstone, “Handbook of Applied Cryptography, CRC Press,
1997”.
[3] M. Gardner, “Codes, Ciphers, and Secret Writing, Dover Publications, Inc., 1972”
[4] L. Smith, “Cryptography the Science of Secret Writing, Dover Publications, Inc., 1943”.
[5] John D. Carpinelli, “Computer Systems Organization & Architecture”
208