CS 142 Lecture Note 2016-2
CS 142 Lecture Note 2016-2
CS142
INTRODUCTION TO COMPUTER SCIENCE
(3 units)
LECTURE NOTES
2015/2016 session
1|Page
CS142 INTRODUCTION TO COMPUTER SCIENCE (3UNITS)
CS142
INTRODUCTION TO COMPUTER SCIENCE
LECTURE NOTES
Introduction to Computers
The word Computer comes from the word “compute” which means to calculate. Just as a driver drives a
vehicle, a welder welds the iron rods, a tiller puts the tiles, a computer is normally considered to be a
calculating device that can perform arithmetic operations at enormous speed (E.g. : millions of calculations
per second) which in all sense is true. But today more than 80% of the work done by the computers is of non
mathematical or non numeric nature.
A computer may be defined as a device that operates upon data or information. A computer can store,
process and retrieve data as and when desired. Hence it may, be referred to as data processor. As a data
processor a computer may gather data from different incoming data sources, merge them (process of mixing
or putting together), sort them (arrange them in desired fashion) and finally print them in the desired
format. None of them is an arithmetic operation.
Hence we can define computer
As an electronic, data processing device that takes the data as input from external world,
processes the same, store the same and generates the output in the desired fashion.
2|Page
CS142 INTRODUCTION TO COMPUTER SCIENCE (3UNITS)
8. No Feelings: Computers are devoid of feelings and emotions. They have no instincts and feelings, as
they are machines. Computers cannot make judgments on their own; their judgments are based on
the instructions given to them in form of programs written by humans.
The earliest device or rather the most primitive device that qualifies as a computer is “abacus” or “soroban.”
This device permits the users to represent the numbers by positions of beads on a rock. Simple addition and
subtraction can be carried out rapidly and efficiently by positioning the beads appropriately..
Another manual calculating device was John Napier’s cardboard multiplication calculator commonly called
Napier’s Bone. It was designed in early 17th century and their upgrade versions were in use even around
1890.
Blasé Pascal invented the first mechanical adding machine in 1642. Later in the year 1671, Baron Gottfried
Wilhelm Von Leibniz of Germany invented the first calculator for multiplication. Keyboard machines,
originated in United States around 1880 and is extensively used till today.
Around this period only Dr. Herman Hollerith came up with the concept of punched cards and Census
Machine that read those cards. These cards were extensively used as an input media in primitive digital
computers. Business machines and calculators made their appearance in Europe and America towards the
end of 19th century.
Charles Babbage, a Professor at Cambridge University in 19th century is considered to be the Father of
modern digital computers. During his period, mathematical and statistical tables were prepared manually by
clerks who after much precaution contained many errors. So Babbage started thinking of building a machine
that could compute tables guaranteed to be error free. In this process Babbage designed a prototype called
“Difference Engine” in the year 1822 which could produce reliable tables. In the year 1842, Babbage came
out with the new idea of “Analytical Engine” that was intended to be completely automatic. It was to be
capable of performing basic arithmetic functions for any mathematical problems at an average speed of 60
additions per minute. Unfortunately, Babbage could not produce the working model of this machine because
precision engineering required to manufacture these machines were unavailable that time. But his efforts
established a number of principles which have been the fundamental steps towards the designing of any
digital computer
Some well known early computers are;
It was capable of performing 5 basic arithmetic operations viz. addition, subtraction, multiplication, division,
and table reference. A number as big as 23 decimal digits could be used in this machine. It took
approximately 0.3 seconds to add two numbers and 4.5 seconds to multiply two numbers.
3|Page
CS142 INTRODUCTION TO COMPUTER SCIENCE (3UNITS)
The Atanasoff Berry Computer (1939 – 1942)
This electronic machine was developed by Dr. John Atanasoff to solve certain mathematical equations. It
was called Atanasoff Berry Computer or “ABC” after its inventors Atanasoff and his assistant Clifford
Berry. It used 45 vacuum tubes for its internal logics and capacitors for storage purposes.
The history of computer development is often, referred to in reference to the different generations of
computing devices. Each generation of computer is characterised by a major technological development that
fundamentally changed the way computers operate, resulting in increasingly smaller, cheaper, and more
efficient and reliable devices. These generations are as follows;
Second generation computer moves from cryptic binary machine language to symbolic, or assembly
languages which allowed programmers to specify instructions in words. It also sees the development of High
level language, such as early version of COBOL, and FORTRAN. These were also the first computers that
stored their instructions in their memory, which moved from magnetic drum to magnetic core technology.
Advantages
a. Smaller in size as compared to first generation computers.
b. They were more reliable.
c. Lesser heat was generated from them
d. These computers were able to reduce the computing time from milliseconds to microseconds.
e. Less prone to hardware failure.
f. Better Portability
g. Wider commercial use.
Disadvantages
a. Air conditioning required
b. Frequent maintenance required.
c. Manual assembly of individual components into a functioning unit was required.
d. Commercial production was difficult and costly as many thousands of individual components had to
be assembled manually into functioning circuits.
e. The manual assembly of individual components and cost of labour involved at this assembly stage
made the commercial production of these computers difficult and costly.
5|Page
CS142 INTRODUCTION TO COMPUTER SCIENCE (3UNITS)
Jack Kilby created the first integrated circuit at Texas Instruments to prove that resistors and capacitors
could exist on the same piece of semiconductor material. His circuit consisted of a sliver of germanium with
five components linked by wires.
Instead of punch cards and printouts, users interacted with third generation computers through keyboards,
monitors and interfaced with an operating system, which allowed the device run many different applications
at one time with a central program that monitored the memory. Computers for the first time became
accessible to a mass audience because they were smaller and cheaper than their predecessors.
Advantages
They were smaller in size as compared to previous generation computers.
They were even more reliable than second generation computers.
Even lesser heat generated than second generation computers.
These computers were able to reduce the computational time from microseconds to nanoseconds.
Maintenance cost was low as hardware failure was less.
They were easily portable.
They were designed for totally general purpose usage. Widely used for various commercial
applications all over the world.
They had less power requirement than previous generation computers.
Manual assembly of individual components into a functioning unit not required. Thus, human labour
and cost involved at assembly stage reduced drastically.
Commercial production of these machines was easier and cheaper.
Disadvantages
Air conditioning was still a prime requirement.
Highly sophisticated technology was required for the manufacture of the ICs.
4. Fourth Generation Computers (1971- Present: Microprocessors)
Initially the integrated circuit contained only 10-20 components. This technology was termed as small scale
integration. Later with the advancement in technology for manufacturing ICs, it became possible to integrate
up to a 100 components on a single Chip. This technology was called Medium Scale Integration or MSI, after,
came the era of Large Scale Integration (LSI) where it became possible to integrate over 30,000 components
onto a single chip. Efforts continued for further miniaturization which resulted in incorporation of millions of
components onto a single chip. This technology which is still in use till date is termed a VLSI (Very large Scale
Integration). The fourth generation computers had the VLSI chips that formed the brain of this generation of
machines and is called Microprocessor.
Advantages
They are smallest in size because of the high component density.
They are very reliable.
6|Page
CS142 INTRODUCTION TO COMPUTER SCIENCE (3UNITS)
The heat generated by these systems is negligible so no specific requirement of air conditioning
systems is there except if desired by users for their comforts.
They are much faster in computation than their previous generation counterparts.
The hardware is failure minimum in these machines.
They require very less maintenance then their predecessors.
They are easily portable because of their small size.
These are totally general purpose machines and could be used in any disciplines.
They involve minimal Labour and cost involved at the assembly stage.
They are cheapest among all generations.
Disadvantages
They require highly sophisticated technology for the manufacture of VLSI chips.
The goal of this generation is to develop devices that respond to natural language input and are capable of
learning and self-organisation.
7|Page
CS142 INTRODUCTION TO COMPUTER SCIENCE (3UNITS)
1. Microcomputer
A microcomputer is the smallest general purpose processing system that can execute program instructions
to perform a variety of tasks. They are further classified as Personal Computers and Home Computers.
Typical of the PC category is the IBM-PC which has become the world standard for Personal Computers in
the office.
2. Minicomputers
A minicomputer may be defined as a small general-purpose computer that is capable of handling large
amount of data from multiple users working simultaneously. Today’s mini systems are costlier and have
large storage capacity speed of arithmetic operations, and ability to support a greater variety of faster-
operating peripheral devices as compared to PCs. Further, while most PC systems remain oriented toward
single users, mini systems are usually designed to simultaneously handle the processing needs of multiple
users.
3. Mainframes
A computer that is more powerful than a mini is called a mainframe computer. Mainframe computers are
capable of handling a large number of application programmers. Most of the application packages designed
in the past by the larger software development firms have been written for mainframe computers. All
popular high level programming languages can be used on available for mainframes, and their operating
system programs offer very high level of sophistication.
4. Supercomputers
Supercomputers are the most powerful and the most expensive computers so far made. Only few of these
computers are produced each year, because only few organizations need their processing capabilities.
Supercomputers are a national resource. The calculations needed in some scientific research and
development areas simply cannot do without Supercomputers. These computers are used in energy sector
space exploration, medicine, industry, and other critical areas.
A computer is a machine that can be programmed to accept data (input), process it into useful information
(output), and store it away (in a secondary storage device) for safekeeping or later reuse. To function, a
computer system requires four main aspects of data handling: input, processing, output, and storage. The
processing of input to output is directed by the software but performed by the hardware. A computer
therefore comprises of both hardware and software components.
A computer requires instructions that direct how data should be processed to produce the desired output.
These instructions are called a 'software program'. Software allows the hardware to do something
useful; without software, the hardware wouldn't know what it was supposed to do. So software depends on
hardware and hardware depends on software.
Software programs are stored as files on a storage device such as the hard disk, DVD or memory sticks.
When they need to run, they are loaded into the computer's memory (RAM).
8|Page
CS142 INTRODUCTION TO COMPUTER SCIENCE (3UNITS)
storage, hard drive disk (HDD), system unit (graphic cards, sound cards, memory, motherboard and chips),
etc. all of which are physical objects that can be touched.
Input devices accept data in a form that the computer can use; they then send the data to the
processing unit.
The processor, more formally known as the central processing unit (CPU), has the electronic circuitry
that manipulates input data into the information people want. The central processing unit executes
computer instructions that are specified in the program.
Output devices show people the processed data-information in a form that they can use.
Storage usually means secondary storage. Secondary storage consists of devices, such as diskettes,
which can store data and programs outside the computer itself. These devices supplement the
computer's memory, which, as we will see, can hold data and programs only temporarily.
The hardware devices attached externally to the computer are called peripheral equipment. Peripheral
equipment includes all input, output, and secondary storage devices. In the case of personal computers,
some of the input, output, and storage devices are built into the same physical unit. In many personal
9|Page
CS142 INTRODUCTION TO COMPUTER SCIENCE (3UNITS)
computers, the CPU and disk drive are all contained in the same housing; the keyboard, mouse, and
screen are separate.
In larger computer systems, however, the input, processing, output, and storage functions may be in
separate rooms, separate buildings, or even separate countries. For example, data may be input on
terminals at a branch bank and then transmitted to the central processing unit at the headquarters bank.
The information produced by the central processing unit may then be transmitted to the international
offices, where it is printed out. Meanwhile, disks with stored data may be kept in bank headquarters and
duplicate data kept on disk or tape in a warehouse across town for safekeeping.
Although the equipment may vary widely, from the simplest computer to the most powerful, by and
large the four elements of a computer system remain the same: input, processing, output, and storage.
Input is the data that you put into the computer system for processing. Input is done by connecting some
specialized peripheral devices to the computer via ports. Some examples of input devices include...
Keyboard: Used to select or enter commands, enter text, QWERTY keyboards are not particularly
user friendly but they are likely to be replaced by voice/speech recognition at some as yet
unspecified time in the future.
Mouse: Used to move the cursor, select commands and features from the on-screen menus, also
used for many actions in drawing diagrams.
Digitising Tablets and the associated puck are used to move the cursor, select commands and
features, enter co-ordinates, mainly used for computer aided drawing (CAD) or map making.
Joysticks can be used to move the cursor, select commands and features, but they are not often used
for general work as they are slower than a mouse. However they are commonly used in computer
games.
Output is usable information; that is, raw input data that has been processed by the computer into
information. The most common forms of output are words, numbers, and graphics. Word output, for
example, may be the letters and memos prepared by office people using word processing software. Other
workers may be more interested in numbers, such as those found in formulas, schedules, and budgets. In
many cases numbers can be understood more easily when output in the form of charts and graphics.
Output devices are peripheral devices which are used to present, to a human operator, the result of the
programming instructions on the data provided. The most common output devices are computer screens
and printers. You can produce output from a computer in other ways, including film and voice output. Some
common output devices include:
10 | P a g e
CS142 INTRODUCTION TO COMPUTER SCIENCE (3UNITS)
Ports: Are connections by which the CPU can pass data to the outside world as raw data for use by
other computers or electronic devices.
Primary Storage
Computer memory, also known as primary storage, is closely associated with the central processing unit but
separate from it. Memory holds the data after it is input to the system and before it is processed; also,
memory holds the data after it has been processed but before it has been released to the output device. In
addition, memory holds the programs (computer instructions) needed by the central processing unit.
Memory is a fast storage for moving data to and from the CPU very quickly. A computer has two types of
memory: RAM and ROM.
1. Random Access Memory (RAM): This type of memory specifically holds programs and data that the
user is currently working on. These include operating system files, device drivers, applications and
currently active data files. Every program that needs to run and data that is being processed is held in
RAM. In current multi-tasking computers, this means that several programs and multiple user files
could reside in memory at once.
RAM is volatile because it only holds data temporarily while the computer is powered on. When a computer
is switched off or re-booted, all the data stored in the RAM is lost. RAM’s major application is to provide fast
access to data and programs for the CPU. This type of storage is more expensive than other types of
secondary storage.
2. Read Only Memory (ROM) This type of memory is a permanent or non-volatile memory store and is
used to store data or applications which the computer needs in order to function. These may be...
Character sets, internal programs such as the BIOS, certain device drivers that control the disks,
cooling fans etc. The data in ROM is permanently burnt into the memory chips during manufacturing
and cannot be erased or deleted.
The data in ROM is used to boot a computer and likewise when the computer is operating the CPU
frequently accesses critical data from ROM that it uses for its operation.
There are other types of ROM that are electrically alterable or re-programmable, but the principle is the
same. The information is retained when the power is switched off. They can only be re-programmed by a
deliberate act and sometimes requires removal from the circuit board concerned. Reprogramming the ROM
in modern computers is simpler and can be done by a process known as flashing. Flashing enables the user
to download a program from the manufacture’s site and follow strict instructions on how to use the
program. If problem occurs during this process, the computer becomes unusable.
Reprogramming ROM is rarely required and may only be needed to support newer hardware or technology
that was not available when the current version of ROM was produced by the manufacturer.
Secondary Storage
Secondary storage provides additional storage separate from memory. Secondary storage has several
advantages. For instance, it would be unwise for a college registrar to try to keep the grades of all the
11 | P a g e
CS142 INTRODUCTION TO COMPUTER SCIENCE (3UNITS)
students in the college in the computer's memory; if this were done, the computer would probably not have
room to store anything else. Also, memory holds data and programs only temporarily.
Secondary storage is needed for large volumes of data and also for data that must persist after the computer
is turned off. Because secondary storage costs less it is convenient to use secondary storage to hold large
amounts of data. All forms of data including the operating system files, application files and user data are
stored in secondary storage.
Usually during a computer operation, only the required programs and user data will be copied to RAM from
the secondary storage.
Backing store memory is usually some type of magnetic storage media i.e. magnetic cassette tape or
magnetic disks (both hard and floppy), but other media forms can be used including punched paper tape,
punched cards, plastic media and CD-ROMs (including DVDs).
An example of memory hierarchy, which is common to most computer Architecture is given below;
Registers are built from fast multi-ported memory cells. They must be fast: a register must be able to drive
its data onto an internal bus in a single clock cycle. They are multi-ported because a register must be able to
supply its data to either the A or the B input of the ALU and accept a value to be stored from the internal
data bus.
In a modern processor, it's considered necessary to have at least 32 registers for integer values and often 32
floating point registers as well. Thus the register file is a small, addressable memory at the top of the
memory hierarchy.
Cache Memory
A CPU cache is a memory used by the central processing unit (CPU) of a computer to reduce the average
time to access data from the main memory. The cache is a smaller, faster and more expensive memory
which stores copies of the data from frequently used main memory locations.
The CPU uses cache memory to store instructions that are repeatedly required to run programs, improving
overall system speed. When the processor needs to read from or write to a location in main memory, it first
checks whether a copy of that data is in the cache. If so, the processor immediately reads from or writes to
the cache, which is much faster than reading from or writing to main memory.
The advantage of cache memory is that the CPU does not have to use the motherboard’s system bus for
data transfer. Whenever data must be passed through the system bus, the data transfer speed slows to the
motherboard’s capability. The CPU can process data much faster by avoiding the bottleneck created by the
system bus.
Computers store data in digital format. This is represented by either 0 or 1. Each 0 or 1 value is called a bit
(short for binary digit) and is the smallest unit of data a computer can handle. Eight bits grouped together as
a unit form a byte. A byte provides upto 28 (i.e 256) different combinations of 0s and 1s to represent data.
Byte 8 bits
13 | P a g e
CS142 INTRODUCTION TO COMPUTER SCIENCE (3UNITS)
Gigabyte (GB) 1,024 Megabytes
The computer does its primary work in a part of the machine we cannot see, a control center that
converts data input to information output. A computer processor is the center of activity. This control
center, also called the central processing unit (CPU), is a highly complex, extensive set of electronic
circuitry that executes stored program instructions as well as communicates with the input, output, and
storage devices.
The processor is totally solid state with no moving parts. It is usually fabricated on one thin plate of doped
silicon with circuitry architecture that is incredibly small, resulting in short transmission paths and high data
rates. The CPU interprets and executes program instructions,
It is the central processing unit that actually transforms data into information. Data is the raw material to be
processed by a computer. Such material can be letters, numbers, or facts like grades in a class, baseball
batting averages, or light and dark areas in a photograph. Processed data becomes information, data that is
organized, meaningful, and useful. In school, for instance, an instructor could enter various student grades
(data), which can be processed to produce final grades and perhaps a class average (information). Data that
is perhaps uninteresting on its own may become very interesting once it is converted to information. The
raw facts (data) about your finances, such as a paycheck or a donation to charity or a medical bill may not be
captivating individually, but together, these and other acts can be processed to produce the refund or
amount you owe on your income tax return (information).
As mentioned earlier, the CPU interacts closely with primary storage, or main memory, referring to it for
both instructions and data. The CPU organises all the functions of the computer system and consists of three
sections.
14 | P a g e
CS142 INTRODUCTION TO COMPUTER SCIENCE (3UNITS)
The Control Unit ... Co-ordinates all the computers functions by interpreting and carrying out the instruction
sent to it by an input device or program.
The control unit contains circuitry that uses electrical signals to direct the entire computer system to carry
out, or execute, stored program instructions. The control unit does not execute program instructions; rather,
it directs other parts of the system to do so. The control unit must communicate with both the
arithmetic/logic unit and memory.
ALU (Arithmetic Logic Unit): the arithmetic/logic unit (ALU) contains the electronic circuitry that executes all
arithmetic and logical operations.
The arithmetic/logic unit can perform four kinds of arithmetic operations, or mathematical calculations:
addition, subtraction, multiplication, and division. As its name implies, the arithmetic/logic unit also
performs logical operations. A logical operation is usually a comparison. The unit can compare numbers,
letters, or special characters. The computer can then take action based on the result of the comparison. This
is a very important capability. It is by comparing that a computer is able to tell, for instance, whether there
are unfilled seats on airplanes, whether charge- card customers have exceeded their credit limits, and
whether one political candidate has more votes than another.
A computer can simultaneously test for more than one condition. In fact, a logic unit can usually discern six
logical relationships: equal to, less than, greater than, less than or equal to, greater than or equal to, and not
equal.
A machine cycle also called is the basic operation performed by a central processing unit (CPU). It is the time
period during which one instruction is fetched from memory and executed when a computer is given an
instruction in machine language.
15 | P a g e
CS142 INTRODUCTION TO COMPUTER SCIENCE (3UNITS)
The machine cycle is a 4 process cycle that includes reading and interpreting the one instruction, executing
the code and then storing that code.
A machine cycle has several synonyms that include processor cycle, fetch-and-execute cycle, fetch-decode-
execute cycle.
Step 1. Fetch - The first step the CPU carries out is to fetch some data and instructions (program)
from main memory then store them in its own internal temporary memory areas. These
memory areas are called 'registers'.
This is called the 'fetch' part of the cycle. For this to happen, the CPU makes use of a vital
hardware path called the 'address bus'. The CPU places the address of the next item to be
fetched on to the address bus.
Data from this address then moves from main memory into the CPU by travelling along
another hardware path called the 'data bus'.
Step 2. Decode - The next step is for the CPU to interpret the instruction it has just fetched. This
process is called 'decode'.
The CPU is designed to understand a specific set of commands. These are called the
'instruction set' of the CPU. Each make of CPU has a different instruction set.
A CPU’s instruction set is stored in ROM. The CPU then translates the retrieved instruction
into a series of computer commands.
Step 3. Execute – This is the part of the cycle when data processing actually takes place. The
instruction is carried out upon the data (executed). The result of this processing is stored in
yet another register.
Step 4. Store – In this final step the result generated by the operation is stored in the main memory,
or sent to an output device. Again the CPU places the address of where the results will be
stored on to the address bus and the result is moved to the specified address via the data bus.
CPU Speed.
The first and second steps take place in the control unit whereas steps three and four occur in the ALU.
16 | P a g e
CS142 INTRODUCTION TO COMPUTER SCIENCE (3UNITS)
Speed of a CPU
A computer can only process one instruction at a time. But the immense speed of the computer enables it to
do millions of such steps in a second.
To the user it may appear that many things are happening simultaneously, for example you may be listening
to music while writing an essay and also downloading some software from the internet. But in reality,
computers can only do one thing at a time. It is just that the machine is processing so fast that everything
seems to happen at once.
A CPU processes digital data by taking each piece of data one-at-a-time and performing an action on it. The
amount of time that it has to process each piece of data is controlled by a quartz clock inside the CPU.
With every tick of the clock, the CPU is able to process one piece of data or execute just one instruction.
The CPU clock speed is measured in cycles per second. 1 cycle per second is also known as 1 Hertz. A
computer running at 1GHz can carry out a thousand million instructions per second.
The clock on a modern desktop computer runs extremely quickly, typically three thousand million times a
second (3 GHz).
It is hard to imagine just how fast this is, but it does mean that a CPU running at this clock speed can handle
a huge amount of data in a very short time. This is why you can listen to music on the computer while you
are also browsing the web and doing some work.
Naturally the speed of the clock determines the basic performance of the CPU - the faster it goes, the more
powerful the computer.
Data is transferred internally within the circuitry of the computer along electrical channels. Each channel,
called a bus, allows various devices inside and attached to the system unit to communicate with each other.
The bus contains multiple wires (signal lines) that contain addressing information that describes the memory
location of where the data is being sent or where it is being retrieved. Each wire in the bus carries a single bit
of information, which means the more wires a bus has the more information it can address.
17 | P a g e
CS142 INTRODUCTION TO COMPUTER SCIENCE (3UNITS)
The bus width, or size of the bus, determines the number of bits that can be transferred at one time. The
larger the bus width, the fewer number of transfer steps required and the faster the transfer of data. In most
computers word size (the number of bits the CPU can process at a given time) is the same as the bus width.
A computer has two basic types of buses. The internal bus or system bus carries data within the
motherboard. The external bus or expansion bus carry data to peripherals and other devices attached to the
motherboard. Buses are of three types:
Data Bus: the data bus is used to transfer data to and from the CPU, main memory, and peripheral
devices. The number of lines or wires in data bus affects the speed of data transfer between
different components. The data bus consists of 8, 16, 32, or 64 lines. A 64-line data bus can transfer
64 bits of data at one time.
Address Bus: the address bus is used to specify the physical address of data or instructions between
memory and the CPU. When a processor or DMA-enabled device needs to read or write to a memory
location, it specifies that memory location on the address bus (the value to be read or written is sent
on the data bus). The width of the address bus determines the amount of memory a system can
address. For example, a system with a 32-bit address bus can address 232 (4,294,967,296) memory
locations. If each memory address holds one byte, the addressable memory space is 4 GB.
The address bus is a unidirectional bus. It can carry information only in one direction.
Control Bus: the control bus is used to send out signals to coordinate and manage the activities of
the motherboard components. It transmits commands or control signals from the CPU and returns
status signals from the components.
18 | P a g e
CS142 INTRODUCTION TO COMPUTER SCIENCE (3UNITS)
- Timing information: It specifies the time for which a device can use data and address bus.
- Command Signal: It specifies the type of operation to be performed.
Classifications of software
Practical computer systems divide software systems into three major classes, system software, programming
software and application software, although the distinction is arbitrary, but the two major categories of
software including system software and applications software.
System software is the software used to manage and control the hardware components and allows
interaction between the hardware and the other types of software. System software comprise of the
Operating System, utility programs and drivers that manage computer resources at a low level.
1. Utility software performs specific tasks related to the management of computer functions. They help
analyze configure, optimize and maintain the computer. Operating systems typically contain the necessary
tools for this, but separate utility programs can provide improved functionality.
Examples of utility programs are antivirus software, backup software and disk tools. Let's look at each of
these in a bit more detail.
Antivirus software, as the name suggests, helps to protect a computer system from viruses and other
harmful programs. A computer virus is a computer program that can cause damage to a computer's
software, hardware or data. It is referred to as a virus because it has the capability to replicate itself
and hide inside other computer files; e.g
Backup software, they are software that are used to copy files and keep incase computer develop a
problem (Crash).
Disk tools are tools that are used to manage hard disk drives and other storage devices. E.g disk scan,
disk cleaners to remove any unnecessary files, and disk defragmenters to re-organize file fragments
on a hard disk drive to increase performance..
2. Device driver is a computer program that controls a particular device that is connected to your
computer. Device drivers act as a translator between the operating system of the computer and the device
connected to it. For many types of devices, the necessary drivers are built into the operating system. When
you plug in a device, the operating system starts looking for the right driver, installs it and you are ready to
start using the device. This is referred to as plug-and-play and is much preferred over having to manually
install the correct drivers.
19 | P a g e
CS142 INTRODUCTION TO COMPUTER SCIENCE (3UNITS)
3. An Operating System (OS) is a set of programs that manage computer hardware resources and
provide common services for application software. The operating system is the most important type of
system software in a computer system. Every general-purpose computer must have an operating system to
run other programs. It manages the computer's memory, processes, and all of its software and hardware. It
also allows you to communicate with the computer without knowing how to speak the computer's
"language."
The operating system's tasks, in the most general sense, fall into six categories:
Processor management
Memory management
Device management
Storage management
Application interface
User interface
The purpose of systems software is to unburden the applications programmer from the details of the
particular computer complex being used, including such accessory devices as communications, printers,
readers, displays and keyboards, and also to partition the computer's resources such as memory and
processor time in a safe and stable manner.
Programming software
Programming software usually provides tools to assist a programmer in writing computer programs, and
software using different programming languages in a more convenient way. The tools include:
i. Compiler
ii. Debuggers
iii. interpreter
iv. linkers
v. text editors
An Integrated development environment (IDE) is a single application that attempts to manage all these
functions.
Application software
Application software allows end users to accomplish one or more specific (not directly computer
development related) tasks. Typical applications include:
20 | P a g e
CS142 INTRODUCTION TO COMPUTER SCIENCE (3UNITS)
Other example of application software are; industrial automation, business software, computer games,
quantum chemistry and solid state physics software , telecommunications, educational software, medical
software, military software, molecular modelling software, image editing, decision making software. Etc
Computer touched our lives from different angles. It is often difficult to mention any discipline or area of
human endeavour where computer are not heavily relied upon. Computer has become part of today’s
modern societies.
Computers are versatile. They can be employed to solve different kinds of problems. For example,
computation of organization’s payroll, computation of students’ CGPA in tertiary institutions, processing of
orders and inventory control in business, ecommerce applications, airline reservation applications, managing
monetary transactions in banks, games, simulation of complex scientific and engineering processes, and
many more.
Computer frees people from repetitive and boring tasks. Computer allows us to do tasks more efficiently,
quickly, and accurately than we could by hand – if at all we could do them by hand. In order for this powerful
machine (computer) to be a useful tool, it must be programmed. That is, we must specify what we want the
computer to do and how it should be carried out. We do this through programming. – that is, writing
programs.
The hardware gets its versatility from its ability to be programmed to do different jobs.
Problem solving using computer involves instructing computer to solve problems. The only way to instruct
computer to carry out task is to provide or write program.
Computer program is a set of instructions that computer follows to carryout task. Computer program tells
computer what to do. Software is a set of instructions that direct the operation of computer system.
The term software and program are often used interchangeably because they essentially refer to the same
thing – instructions that direct computer to perform task. However, technically, software is like general term
which comprises of the program (set of instructions), the configuration data and all the necessary
documentation that users required to operate the software correctly.
Programming is an act of writing computer programs. A person who writes computer program is a called
programmer. Computer programs are not written in English, French, or any other natural languages familiar
to you. Instead, computer programs are written using artificial formalisms called programming language.
Programming language is an artificial formalism purposely created for instructing computer to carry out a
particular task. There are many programming languages in existence. Examples of programming languages
are:, FORTRAN, BASIC, Pascal, C, C++, Haskel, Python, Perl, MATLAB, Java, C#, PHP, Objective C, etc.
Programming languages broadly are classified into two; low level language and high level
1. Low level languages are programming language that provides little or no abstraction of the computer
system. Low level languages are sometimes described as being "close to the hardware” rather than being
closer to human languages. Low level languages are machine dependant. Programming using them is difficult
21 | P a g e
CS142 INTRODUCTION TO COMPUTER SCIENCE (3UNITS)
and it requires extensive knowledge of the hardware. Machine language and assembly language are popular
examples of low level languages.
Machine Language – In machine language, 0s and 1s (binary digits) are used to specify
instructions. This is the language that computer understands directly. It is difficult to learn and also
difficult to write programs using it.
Assembly Language – In this language, symbolic codes called mnemonics are used instead of
the 0s and 1s. Programming in assembly language is simpler compared with programming using
machine language. For computer to execute program written in assembly language, a translator
called ASSEMBLER is required.
2. High level languages are programming languages that provides high degree of abstraction of the
underlying hardware. It hides the complexity of computer's instruction set architecture. High level languages
are closer to human languages. They contain some terminologies similar to those used in human languages.
The programming languages mentioned above (FORTRAN, BASIC, Pascal, C, C++, Haskel, python, Perl,
MATLAB, Java, C#, PHP, Objective C, etc) are all high level languages.
The main advantage of high-level languages over low level languages is that programs written using high
level language are easier to read and understand. Programs written using low level languages are often
difficult to understand.
Language translators are software that; after a program has been written using any of the high level
language, a language translator is needed to translate the program into its equivalent machine executable
form. The reason behind the translation is because computer only understands instructions in 0s and 1s
format (binary digits). Data and instructions are represented in digital computers in 0s and 1s. The
representation of data or instructions in the computer’s memory is a stream of bits (binary digits).
Therefore, the work of language translator is to translate source code to object code which computer uses
for execution.
Programs or software are created to solve problems. In the process of creating the programs programmers
do follow series of steps. These series of steps form what is known as PDLC.
Thus, to write a program, it is recommended to follow some steps in PDLC. These steps are equally called the
problem solving steps using computer.
PDLC is composed of distinct phases or activities that a program undergoes right from initial stage of its
development to completion. The steps of PDLC are:
22 | P a g e
CS142 INTRODUCTION TO COMPUTER SCIENCE (3UNITS)
1. Understanding the problem
2. Problem analysis and specification
3. Problem design and algorithm development
4. Coding
5. Testing Understand Problem analysis
6. Documentation the problem and specification
7. Maintenance
Maintenance
Testing
Documentation
Figure 12:
The steps of PDLC can be grouped into two distinct phases: problem solving and implementation
23 | P a g e
CS142 INTRODUCTION TO COMPUTER SCIENCE (3UNITS)
e. Testing
Testing is the process of running program with the intention of finding bugs or error. Once the
algorithm has been implemented or written using a programming language, it can be run or executed
with different set of data to see the results (output) it produces. The essence of running it with
different sets of data is to find out whether it produces expected result and whether it ultimately
meets its specification or not.
When a program is run, if all is well, you should see correct output. However, it is possible for the
program to produce wrong results (output)or failed to run at all. In that case, it is possible that the
algorithm is not properly implemented. Therefore, the program is said to contain bugs or errors.
Therefore, you should debug it….
f. Debugging is the process of finding and fixing errors or bugs in programs. It is often a very time –
consuming task, since the programmer must read the code line by line in an attempt to uncover
error. During testing, the programmer will be looking for both syntax errors and logic errors, as well
as exploring other section that may cause the program to either not work properly or not run at all.
g. Documentation
Documentation includes written explanations of the problem being solved and the organization of
the solution, comments embedded within the program itself, and user manuals that describe how to
use the program. Documentation is a task that should be done right from the first stage of program
development. Many different people are likely to work on a program over a long period of time. Each
of those people must be able to read and understand the code.
h. Maintenance
Program/software maintenance can be described as the modifications or changes that can be made
to software after it has been put into use. Once a program has been put into use, it is often necessary
to modify it. Modification may involve fixing an error that is discovered during the use of the program
or changing the program in response to changes in the user’s requirements. Each time the program is
modified, it is necessary to repeat the problem-solving and implementation phases for those aspects
of the program that changed. This phase of the software development process (maintenance)actually
accounts for the majority of the effort expended on most programs.
So far, we came across some strange terminologies like pseudo code, flowchart and programming errors.
The following section presents brief notes on them.
3.4 Algorithms
An algorithm is a precise and unambiguous sequence of instructions for solving a problem. Algorithm can
also be defined as a finite and unambiguous step-by-step procedure to accomplish a task. The term
algorithm is not only restricted to the field computer science alone, it applies to any method of solving a
problem.
Algorithm is not the same as a program. Algorithm is more like an idea of the steps a computer will follow to
perform a task. Algorithms can be written or expressed in any language.
We use algorithms every day. Recipes, instructions, and directions are all examples of algorithms. When you
start your car, you follow a step-by-step procedure (algorithm) –the algorithm for starting a car might look
something like this:
24 | P a g e
CS142 INTRODUCTION TO COMPUTER SCIENCE (3UNITS)
1. Insert the key.
2. Make sure the transmission is in Park (or Neutral).
3. Turn the key to the start position.
4. If the engine starts within six seconds, release the key to the ignition position.
5. If the engine doesn’t start in six seconds, release the key and gas pedal, wait ten seconds, and repeat
Steps 3 through 5, but not more than five times.
6. If the car doesn’t start, call the garage.
Attributes of an Algorithm
1. Precision
Precision of an algorithm has to do with its ability to give clear and correct solution in all case.
2. Un ambiguity
Ambiguity in algorithm means having more than one step performing the same task. An algorithm is
unambiguous if it doesn’t have series of steps performing the same task.
3. Finite
An algorithm is finite if it ends. That is, it does not be run forever. It must end somewhere.
4. Efficiency
Efficiency of algorithm has to do with how much of various types of resources (processing time and
memory space) it consumes. Some algorithms consume much memory and time when executed. In
computer science, we are interested in algorithms that are time and space (memory) efficient.
An algorithm can be expressed in form of pseudo code. To have a better understanding of the steps in
algorithm, flowchart can be used to represent the algorithm.
Therefore, pseudo code and flowchart are programming tools that help programmers express algorithm in a
way that simplifies implementation.
Pseudo code
Pseudo code is used as a way of describing a computer program without completely following the syntax of
programming language. Alternatively, a pseudo code can be seen as an informal set of instructions that
imitate the structure of a program but does not adhere completely to the syntax of programming language.
3.5 Flowchart
In computer science, one way of understanding the steps in an algorithm is by using flowchart. A flowchart is
a pictorial representation of an algorithm that uses symbols to show the operations and decisions to be
followed by a computer in solving problem. A flowchart is a convenient technique to show the flow of
control in a program. Flowchart is one of the programming tools that help programmers to understand
algorithm better.
In fact, flowcharts are the plan to be followed when the program is written. Expert programmers may write
programs without drawing the flowcharts. But for a beginner it is recommended that a flowchart should be
drawn before writing a program. This reduces the number of errors and omissions that might occur during
program creation.
25 | P a g e
CS142 INTRODUCTION TO COMPUTER SCIENCE (3UNITS)
The explanation of basic flowchart symbols is given below.
Start/Stop symbol
This symbol is used for two purposes: to indicate the starting point (START or BEGIN of the algorithm and to
indicate the end point (END) of the algorithm.
Flow Lines
Flow lines, are arrowheads that are used to indicate the direction of the flow of control in a flowchart. This
means the flow lines indicate the next statement to be executed.
Input/Output symbol
Input/output symbols are used to indicate input/output operations. The input operation is the entry of data
into the computer while the output operation is the display of the result of processing. If the step in the
algorithm requires input, then you have to use this symbol. Similarly, a step is to print or display output, you
have to use this symbol.
Processing Symbol
Processing symbol is used to indicate any processing activity such as assigning value to a variable. Therefore,
all arithmetic operations of adding, subtracting, multiplying, and dividing are represented with processing
symbol.
Decision Symbol
Decision symbol is used whenever decision has to be taken in program. The symbol has one entry point and
at least two exit paths depending upon the outcome of the decision made. The decision is usually in form of
Boolean condition which can be evaluated to ether true or false. When a condition to true, the path marked
“true or yes” is followed. If the condition is false, the path for “false or no” is followed.
Connector Symbol
If a flowchart is too big to be accommodated on page, a connector symbol can be used to indicate the
continuation in another page. It is a circle with a number written inside it. If a flowchart is discontinued at
some point, a circle is drawn pointing away from the chart. Another circle with the same number inside is
placed where the flowchart is continued.
The following are some guidelines or rules that are very important when drawing flowcharts
Advantages of Flowchart
Disadvantages
i. The drawing of flowcharts is a very time-consuming process and laborious especially for large and
complex problems.
ii. It is very difficult to include any new step in the existing flowchart; redrawing of the flowchart is the
only solution and it is even more difficult and time consuming.
iii. If an algorithm has complex branches and loops, flowcharts become very difficult to draw.
Although flowcharts can be visually appealing, pseudo code is often the preferred choice for algorithm
development
3.6 Examples
This section presents example of problem which algorithm, pseudo code, and flowcharts can be written for
them.
Example 1
Write an algorithm to calculate the area of rectangle. Represent the algorithm in a flowchart.
Problem analysis
This problem requires the length and breadth of the rectangle to be specified. Hence it requires input. The
length and breadth can be integer or floating point numbers. So the output (area of the rectangle)should be
floating point number (to generalize the case).
27 | P a g e
CS142 INTRODUCTION TO COMPUTER SCIENCE (3UNITS)
start
Y
area = length * breadth
print area
stop
Algorithm
1. Start
2. Print “please enter the length ”
3. input a number and assign it to a variable length
4. Print “please enter the breadth”
5. input a number and assign it to a variable breadth
6. If length is greater than 0 and breadth is greater than 0 do step 7, 8 and 9, else goto step 2.
7. Multiply length by breadth and assign the result to a variable area
8. Print area.
9. Stop
Pseudo code
Start
Print “please enter the length”
length = number entered by user
Print “please enter the breadth”
breadth = number entered by user
If length >0 and breadth >0
area = length * breadth
Print area.
else
Print “invalid input” and goto step 2.
endIf
Stop
28 | P a g e
CS142 INTRODUCTION TO COMPUTER SCIENCE (3UNITS)
Example 2
Write an algorithm to find the average of positive integers from 1 to 20. (ie, 1,2,3,4,….., 20). Represent the
algorithm in aflowchart.
Problem analysis
This problem does not require any input.All that is needed is to have a variable initialized to 1 and then
continuously incrementthe variableuntil it reaches 20 while accumulating the sum.Theoutput should be a
floating point number.
Algorithm
1. Start
2. Declare a variable n and initialize it to 1(ie, number = 1)
3. Declare a variable sum and initialize it to 0 (ie, sum = 0)
4. Declare a variable average.
5. while n is less than or equal to 20, repeat steps 6 and 7, otherwise goto step 8
6. Add nto sum (sum = sum + n)
7. Increment n by 1 (ie, add 1 to n so that n will point to the next integer in the sequence)
8. Divide sum by 20 and assign the result to average.
Pseudo code
9. Print average start
10. Stop n=1
sum = 0
average
start repeat while n ≤ 20
sum = sum + n
n = n+ 1
n=1 end repeat
sum = 0 average = sum / 20
average print average
stop
n<= 20 N
Y
sum = sum + n
n=n+1
average= sum / 20
print average
stop
29 | P a g e
CS142 INTRODUCTION TO COMPUTER SCIENCE (3UNITS)
Example 3
stop
30 | P a g e
CS142 INTRODUCTION TO COMPUTER SCIENCE (3UNITS)
EXERCISES
1. Write an algorithm or pseudo code that calculates area of a triangle and draw a flowchart for the
algorithm. Your algorithm should deny entry of any value less than 1.
2. Write an algorithm or pseudo code that display “Hello world” ten times, and represent the algorithm
in a flowchart.
3. Given the following algorithm
1. Start
2. Declare a variable N and assign 1 to it (ie, N=1).
3. While N is less than or equal to 10, do steps 4 and 5 and return to step 3, else go
to step 6
4. Print N
5. Increment N by 1(ie, N = N +1)
6. Stop
QBASIC
PREFACE
These notes are an introduction to computer programming using the language QBasic. The lecture note is prepared for
CS142 a 100 level undergraduate students and it is aimed to give you an idea of what programming is all about. If you
faithfully work your way through the note, you will learn how some of the gritty details that programming involves that add
up to the wonderful things called "programs." You will be able to write some simple programs yourself. Despite the fact that
these notes are about programming, but they do not try to make you a programmer. Their goal is to increase your
understanding of computers in the modern world. If you are thinking about becoming a programmer, studying these notes is
a good first step. However, these notes are aimed at students who are both computer science majors and those that are not. .
Introduction
Can you guise why it is called BASIC? I meant what do you suppose is the emphasis of the BASIC computer programming
language? The answer is simple; it is called BASIC because the language emphasizes the BASIC ideas found in all
programming languages. BASIC is an acronym, for– Beginners’ All-purpose Symbolic Instruction Code.
The language BASIC was designed in the early 1960s for teaching the basic principles of programming to non-science
majors. It has been popular ever since. There are many versions of BASIC. These notes use QBasic; a Microsoft released a
version of 1985, it is a version that once came free with Microsoft operating systems. With QBasic you can easily write small
programs and get the idea of what programming is about. Other versions of BASIC are intended for professional
programmers who expect to write programs that are many thousands of lines long. Our programs will not get that long.
Lesson 1
Running Your First Program
Before you can create a program in QBASIC, you need the QBASIC compiler.
QBASIC compiler can be downloaded from the Internet
QBASIC compiler has a startup window with blue background.
The Startup window will normally request you to press optional keys to continue. Press the key that is appropriate.
QBasic on your Computer
If your computer is running any variety of a Microsoft operating system, it can run QBasic.
31 | P a g e
CS142 INTRODUCTION TO COMPUTER SCIENCE (3UNITS)
If you are running a more recent operating system, click on the "Start" button.
o Click on "Run"
o In the "Open" box, enter CMD
o Click "OK" (or hit "Enter")
When you get a window with the prompt, enter the command: qbasic then press the ENTER key.
Press F5 to run the program OR from the menu bar, click Run then Start OR Press Shift + F5.
You should now see a black screen as in fig 1.2 below
32 | P a g e
CS142 INTRODUCTION TO COMPUTER SCIENCE (3UNITS)
QBASIC Program Building Blocks
QBASIC programming language is made up of some fundamental building blocks which are treated as follows:
a. QBASIC Data Types there are various data types in QBASIC and can be classified into two major
categories:
(i.) Constants and
(ii.) Variables
Constant: Constants are numbers within a program whose values do not change.
Constant Declaration
To declare constants of any type (integer, real or string), the keyword used in QBasci is CONST.
Constants can be declared as simply a value or with a descriptive name:
E.g.
CONST CourseUnit = 4.0
CONST CGPA = 4.49
CONST CourseTitle = “CS142”
Variable
Modern computers have a large amount of main memory (also called RAM). This memory is used for many things. When
you run a QBasic program, the statements of the program are stored in main memory. The data for the program also can be
stored in main memory. A variable in QBasic is a small amount of computer memory that has been given a name. You (the
programmer) think of the name you want to use. The QBasic system will use a section of main memory for that name. A
variable is like a small box that holds a value. The value in the variable can change (that is why it is called a variable). Here is
a program that uses a variable:
A Variable in QBASIC is a small amount of computer memory that has been given a name. The location of a
variable in RAM is called the "address.”
Variables enable your program to remember values from one program statement to the next.
A variable is accessed by calling its name. Variable names can have a combination of letters and numbers
In algebra, what do you call symbols like "x" and "y”, as in 3x2 + 2y?
Variable Declaration
There are two methods for variable declaration:
i. Explicit Declaration: Here, you explicitly declare the variable as a type. This is done by using the DIM statement.
33 | P a g e
CS142 INTRODUCTION TO COMPUTER SCIENCE (3UNITS)
state = “Covenant University”
number = 324
profit = 34.987890287
gpa = 4.99
PRINT state
PRINT number, profit, gpa
$ -- String
% -- Integer
& -- Long
! -- Single
# -- Double
With these symbols, variables could be declared and defined with a single statement using the LET keyword.
E.g.
LET x$ = “QBASIC is cool!”
LET x% = 5
LET x& = 92,000
LET x! = 3.725
LET x # = 3.1417583294
34 | P a g e
CS142 INTRODUCTION TO COMPUTER SCIENCE (3UNITS)
Data Types in QBasic
Names for variables must be single words that the programmer picks. The names don't have to be real words, but it they
should wisely choose to help in understanding the program they are. Look over the following rules.
QUESTION :
Which of the following are OK names to use for a variable that will hold a floating point number?
SUM, GRAND TOTAL, MyValue, 16Candles, SUM23, YEAR%
35 | P a g e
CS142 INTRODUCTION TO COMPUTER SCIENCE (3UNITS)
Answer:
o SUM --- OK (made up of correct characters, not too long)
o MyValue --- OK (upper and lower case letters can be used)
o SUM23 --- OK (digits can be used after the first letter)
o GRAND TOTAL --- BAD (no spaces allowed)
o 16Candles --- BAD (digits can't be used as first character)
o YEAR% --- BAD (last character % means this is an integer variable)
As soon as you move the cursor out of the PRINT statement the QBasic system will change your program:
QUESTION :
VALUE is the name of a variable. Which of the following name a different variable?
Answer:
36 | P a g e
CS142 INTRODUCTION TO COMPUTER SCIENCE (3UNITS)
MILES MILE
528.7 0
The arithmetic expression MILE / 12.5 will get the 0 from MILE and divide it by 12.5, resulting in 0. Finally the PRINT will
write to the monitor:
0
This is a bug, and hard to track down unless you carefully look at the spelling of each variable name in the program. If a
program you write mysteriously calculates an incorrect answer of zero, check the spelling of each variable!
QUESTION 11:
What do you think the following program will write to the monitor?
' Calculate Miles per Gallon (Buggy? or not?)
'
LET MILE = (45678.3 - 45149.6)
PRINT MILE# / 12.5
END
Answer:
The program will print:
0
This is because MILE and MILE# are two different names, for two different variables. MILE# was first used in the PRINT
statement, so that is when memory was found for it. It was initialized to zero, so it held a zero when the division MILE# /
12.5 was done.
i. INPUT Command
Syntax
(ii)
37 | P a g e
CS142 INTRODUCTION TO COMPUTER SCIENCE (3UNITS)
? list of variables
OR
? “Prompting Message”, list of variables
In this program, NUM is a variable. The programmer chose the name NUM . When the program runs, several things
happen when the LET statement executes:
Memory is reserved for the variable NUM
The number 23.5 is stored in the variable
So after this statement has executed a section of memory named NUM holds 23.5:
NUM
23.5
After the first statement has executed, the second statement executes:
PRINT "The variable contains", NUM
The variable NUM already exists, so no more memory is reserved for it.
The PRINT statement does several things:
It prints "The variable contains"
It looks in the variable NUM for a number.
It prints out the number it found.
QUESTION:
What do you think the following program will write to the monitor?
' Program with a variable
'
LET VALUE = 2 + 3
PRINT "The result is", VALUE
END
Answer:
The program will print: The result is 5
Saving a Result
Look at this new program again:
38 | P a g e
CS142 INTRODUCTION TO COMPUTER SCIENCE (3UNITS)
' Program with a variable
'
LET VALUE = 2 + 3
PRINT "The result is", VALUE
END
The LET statement can be used with a variable to save the result of arithmetic. The value saved in the variable will stay there
until another statement changes it, or until the program stops running.
QUESTION 4:
What do you think the following program will write to the monitor?
' Saving a result in a variable
'
LET SUM = 1 + 2 + 3
PRINT "The sum is", SUM
END
Answer:
The program will print: The sum is 6
Exercise
Using LET and other relevant commands, write a QBASIC program that finds the area and perimeter of a triangle.
Numeric Functions
These are functions for mathematical calculations provided in the QBASIC compiler. Numeric functions take numbers as
arguments and returns a number as output. Some of these functions are:
Num = ABS(signednumber)
Lectures Topics
o Input and Output in a computer system.
o INPUT statement.
o Prompting the user.
39 | P a g e
CS142 INTRODUCTION TO COMPUTER SCIENCE (3UNITS)
o Entering number data.
o Using several INPUT statements.
Up until now in these notes, all the data a program uses have been part of the program itself. For example:
' Calculate Miles per Gallon
'
LET MILES = 45678.3 - 45149.6
LET GALLONS = 12.5
PRINT MILES / GALLONS
END
The data is the first odometer reading (45149.6), the second odometer reading (45678.3), and the number of gallons.
QUESTION:
Will this program do the same thing each time it is run?
Answer:
Yes.
Input Devices
Consider the program.
LET MILES = 45678.3 - 45149.6
LET GALLONS = 12.5
PRINT MILES / GALLONS
END
Every time you run the program it will do exactly the same thing. The next time you fill up your gas tank again, you
would have to change the program to calculate with the new values. The program is not very useful.
Most useful computer programs input data from various sources when they run. Input means data that comes from
outside the program. A program that does this can work with new data each time it is run.
Sources of Input Data
o The Keyboard
o A Hard Disk
o A Floppy Disk
o A Cd-Rom
o The Mouse
o A Video Camera
o An Audio Digitizer (Part Of A Sound Board)
o The Internet
o Hundreds Of Other Sources
For us, most data will come from the user of a program typing on the keyboard. Some sources of data (like audio
data) require special hardware. A piece of hardware that is a source of input to a computer program is called an
input device.
Output Devices
As they run, most computer programs output data to various places. In programming, output means data that the
program sends outside of itself to some device. For us, output mostly will go to the computer monitor.
40 | P a g e
CS142 INTRODUCTION TO COMPUTER SCIENCE (3UNITS)
o Hundreds Of Other Places
A piece of hardware that uses data from program is called an output device.
QUESTION:
Some devices are on the list of input devices and on the list of output devices. What were some of these devices?
Answer:
o a hard disk
o a diskette
o the Internet
I/O
The hard disk of a computer system is used for both Input to a program and Output from a program. Other devices
are exclusively input devices (such as the keyboard or mouse) or output devices (such as the printer and monitor.)
Input and Output are so important to a computer system that the abbreviation I/O is used. Any device which does
either input, output, or both is called an I/O device. The movement of data from or to such a device is often called
"I/O".
These statements will execute one by one in sequence. To run the program push "shift-F5" or use the menu "alt-R,
S" (as usual).
QUESTION:
What is the first thing the program writes to the monitor?
Answer:
Type a number
Now the second statement INPUT NUMBER executes. The INPUT statement is used to get data from the
keyboard. It will:
o Print a question mark "?" to the screen.
o Wait until the user has typed in a number.
o Get the number when the user hits the "enter" key.
o Put the number in the variable NUMBER.
Just after this statement starts the monitor will look something like:
Type a number
?
The question mark came from the INPUT statement. The INPUT statement is waiting for the user (you) to type a
number. Say that you type 23. Now the monitor looks like:
Type a number
? 23
To enter the number, hit the enter key. The INPUT statement puts the 23 into the variable NUMBER. Next, the
PRINT statement executes.
QUESTION:
What will the monitor finally look like?
Answer:
The program has done both output and input. It output data to the monitor when it wrote "Type a number" and
the "?". It did input from the keyboard when it got the 23 and stored it in NUMBER. Then it did output again when
it wrote 46 to the monitor.
Now hit any key on the keyboard to switch back to the QBasic window from the DOS window.
After each run of the program, push any key to return to the QBasic screen. The picture shows the DOS window
after the program was run three times.
42 | P a g e
CS142 INTRODUCTION TO COMPUTER SCIENCE (3UNITS)
QUESTION:
Does the program work with floating point numbers?
Answer:
Yes. Floating point numbers are those with a decimal point, such as in the second run of the program. The variable
NUMBER can hold floating point values.
The variable should be the correct type for the expected input. Remember that the last character of a variable name
indicates what the variable is expected to hold. For example, a variable VALUE# can potentially hold a very big
floating point number. A variable DATA% is expected to hold an integer (no decimal point). Here is a program that
does input of an integer:
QUESTION:
Say that the user types 1.2 when the INPUT statement of this program asks for data. What will the monitor show
after the user hits "enter"?
Answer:
Type a number
? 1.2
2
The variable DATA% can only hold an integer, which cannot have a decimal point. The user typed 1.2, but only the
1 was put into the variable. (The 1.2 is said to have been truncated to 1). The 1 was then doubled, and 2 was
output.
Control Structure
Loops
Many machines do their work by using repeated motions, cycles. The engine in your car performs the same
motions over and over again as it burns gasoline to provide power. Electric motors are similar; they convert electric
power into spinning motion. Both of these machines are useful because they do the same things over and over and
can keep going as long as we want.
Computer programs, also, use cycles. Much of the usefulness of computer software comes from doing things in
cycles. In programming, cycles are called loops. When a program has a loop in it, some statements are done over
and over as long as is needed to get the work done. Most computer programs execute millions of program
statements each time they are used. Most of these statements are the same statements being executed over and over
many times. This section of the lesson discusses loops in QBasic.
43 | P a g e
CS142 INTRODUCTION TO COMPUTER SCIENCE (3UNITS)
Lecture Topics:
o The DO ... LOOP
o Using CONTROL-BREAK to Exit a Loop.
o The Loop Body.
o Indenting Loop Bodies.
o Sequential Execution And Looping Combined.
o The SOUND Statement.
44 | P a g e
CS142 INTRODUCTION TO COMPUTER SCIENCE (3UNITS)
NUMBER
100
Now the statements inside the loop start again with the first statement after DO:
o For a second time, the PRINT statement prints "Type a number".
o For a second time, the INPUT statement gets a number to put in the variable NUMBER.
o Say that the user typed in 50. The number 50 will replace what was previously in the variable.
o For a second time, the second PRINT statement prints "6% of the number is" and then computes and
prints 50 * 0.06.
o The LOOP statement marks the end of the loop.
At this point, variable NUMBER now has the new value of 50 in it:
NUMBER
50
QUESTION:
What do you suppose happens next? Have the user enter the number 200.
Answer:
The statements inside the loop are executed a THIRD time:
o For the third time, the PRINT statement prints a prompt.
o For the third time, the INPUT statement gets a number to put in the variable NUMBER.
o Say that the user typed in 200. The number 200 will replace what was previously in the variable.
o For the third time, the second PRINT statement prints "6% of the number is" and then computes and
prints 200 * 0.06.
o The LOOP statement marks the end of the loop.
Ending the Loop
Now the monitor shows:
Type a number
? 100
6% of the number is 6
Type a number
? 50
6% of the number is 3
Type a number
? 200
6% of the number is 12
45 | P a g e
CS142 INTRODUCTION TO COMPUTER SCIENCE (3UNITS)
NUMBER
200
The program will continue forever, performing the statements inside the DO ... LOOP again and again. If you run
this program, you will have to stop it, somehow. To stop the program, hit CONTROL-BREAK. (Hold down the key
marked "Ctrl" then tap the key marked "Break.")
QUESTION:
Why not just let the program run until it ends?
Answer:
The program will never end.
Brackets
Look again at the program:
' Example of a loop
DO
PRINT "Type a number"
INPUT NUMBER
PRINT "6% of the number is", NUMBER * 0.06
LOOP
END
The DO and the LOOP are matched like brackets ( ) or [ ]. The statements inside of them will be done over and
over, starting with the first enclosed statement and going on in sequence. You can have as many statements as you
need between DO and LOOP:
QUESTION:
Do you see anything in the DO or the LOOP statement that says how many times the statements between them are
to be repeated?
Answer:
No, neither the DO nor the LOOP (nor the statements between them) say how many times to repeat. The
statements between the DO and the LOOP will be repeated endlessly, or until the user hits CONTROL-BREAK.
A Loop Body
The statements between the DO and LOOP are called the body of the loop. So you can say that for the example
program, the loop body is repeated endlessly. Soon you will learn how to write loops that do not repeat endlessly.
Sometimes, however, endlessly repeating loops are useful.
46 | P a g e
CS142 INTRODUCTION TO COMPUTER SCIENCE (3UNITS)
A Story Problem
Say that you are in charge of putting price tags on new merchandise in a clothing store. A new shipment of several
hundred items has just arrived. You have a list that tells you the wholesale price of each item. The markup in your
store is 50 percent, so the price tag should be 1.5 times the wholesale price. You would like a program that asks you
for the wholesale price of an item and then prints the retail price, and keeps doing that over and over (since you
have hundreds of items).
QUESTION :
In rough outline, what do you suppose the program looks like?
Click here for a .
Answer:
Here is a rough outline for the program:
DO
' ask the user for the wholesale price of an item
' get the price, put it in a variable
' compute and print out the retail price
LOOP
END
Loop Conditions
The DO WHILE statement acts like a "gate keeper" for the loop body: execution is allowed to enter the loop body only
when a certain condition is true. This chapter will discuss how that condition can be described.
Lesson Topics:
o Review of DO WHILE statements.
o The condition part of DO WHILE statements.
o Comparisons between numbers.
o Ending a loop with a Sentinel value.
o Examples of programs using sentinel values.
o General Scheme for DO WHILE loops with sentinels.
QUESTION:
(Review:) What is a loop condition?
Answer:
A loop condition is a test that is part of the DO WHILE statement.
Here the DO WHILE in statement 2 is the loop condition (the gate keeper). Execution enters the loop body only if
COUNT <= 5
That is, only if the number stored in COUNT is less than or equal to 5. Then statements 3 and 4 are executed, and then
LOOP sends execution back to the DO WHILE. The test COUNT <= 5 must be true every time the loop body starts to
execute.
QUESTION:
Say that Statement 4 has just changed COUNT to 5. Now the LOOP statement sends execution back to the DO WHILE.
Will the loop body execute again?
47 | P a g e
CS142 INTRODUCTION TO COMPUTER SCIENCE (3UNITS)
Answer:
YES, because COUNT has a 5 stored in it, and:
COUNT <= 5
^
|
+----- holds a 5
is true because 5 is less than or equal to 5.
So far in these chapters the condition has tested if one number is less than or equal to another number. You can also test if
one number is LESS THAN another number:
COUNT < 5
This tests if COUNT is LESS THAN 5. Here is the program, slightly modified.
' Loop with LESS THAN test
'
LET COUNT = 0 'Statement 1
'
DO WHILE COUNT < 5 'Statement 2
PRINT COUNT 'Statement 3
LET COUNT = COUNT + 1 'Statement 4
LOOP
END
Now the DO WHILE lets execution into the loop body only if COUNT is less than (but not equal) to 5.
QUESTION:
Say that Statement 4 has just changed COUNT to 5. The LOOP statement sends execution back to the DO WHILE. Will
the loop body execute again?
Answer:
NO, because COUNT has a 5 stored in it, and:
COUNT < 5
^
|
+----- holds a 5
is FALSE because 5 is NOT less than 5.
Decision Making
In this section we will look at how computer programs make decisions based on numbers and variables. This is done with a
statement called the IF-THEN-ELSE statement. This is a very useful statement. It will be an important building block in
building up large programs.
Lesson Topics:
Two-way Decisions.
QBasic IF-THEN-ELSE statement.
Outline of a two-way decision.
Relational Expressions.
48 | P a g e
CS142 INTRODUCTION TO COMPUTER SCIENCE (3UNITS)
Relational Symbols.
Example Programs.
QUESTION:
You are driving in your car and it starts to rain. The rain falls on your windshield and makes it hard to see. What should you
do with the windshield wipers?
Answer:
Turn the windshield wipers on.
Two-way Decisions
The windshield wipers are controlled with an ON-OFF switch. The decision to turn the switch on looks like this:
In this picture of a decision, you are supposed to start at the top, then follow the line to the question:
is it raining?
The answer to the question is either TRUE or FALSE.
o If the answer is TRUE,
o follow the line labeled TRUE,do the directions in the box "turn wipers on", follow the line to "continue"
o If the answer is FALSE
o follow the line labeled FALSE,
o do the directions in the box "turn wipers off", follow the line to "continue"
QUESTION:
How many ways can you go from "start" to "continue"?
Answer:
There are two paths through this chart.
49 | P a g e
CS142 INTRODUCTION TO COMPUTER SCIENCE (3UNITS)
The words IF, THEN, ELSE, and END IF are brackets that divide the part of the program into two branches. The ELSE is
like a dividing line between the "true branch" and the "false branch".
The IF statement always asks a question (usually about the number in a variable).
o The answer will be TRUE or FALSE.
If the answer is TRUE only the true-branch is executed.
If the answer is FALSE only the false-branch is executed.
No matter which branch was chosen, execution continues with the statement after the END IF.
A two-way decision is like picking which of two roads to take to the same destination. The fork in the road is the IF
statement, and the two roads come together just after the END IF statement.
QUESTION:
The user runs the program and enters "12". What will the program print?
Answer:
Enter a number
? 12
The number is zero or positive.
Bye
The true branch was executed because the answer to the question NUMBER >= 0 was true.
The Program as a Chart
Here is the program again, done as a chart. Because the answer to the question was "true", the path on the left was done.
The "two-way split" of the program is easy to see in a two dimensional chart. It is harder to see this in a program.
QUESTION:
The user runs the program and enters "-5". What will the program print?
Answer:
Enter a number
? -5
The number is negative.
Bye
ONLY the FALSE branch was executed because the answer to the question NUMBER >= 0 was FALSE.
More than one Statement per Branch
Here is the program again with some added statements:
PRINT "Enter a Number"
50 | P a g e
CS142 INTRODUCTION TO COMPUTER SCIENCE (3UNITS)
INPUT NUMBER
'
IF NUMBER >= 0 THEN
PRINT "The number is zero or positive" ' true branch
PRINT "Positive numbers are > 0" ' true branch
ELSE
PRINT "The number is negative" ' false branch
PRINT "Negative numbers are < 0" ' false branch
END IF
'
PRINT "Bye" ' this statement is always done
END
The statements in the true branch are executed when the question in the IF statement is TRUE. There can be as many
statements as you want in the true branch. The true branch consists of the statements between the IF statement and the ELSE
statement. Of course, the statements in the false branch are executed when the question in the IF statement is FALSE. There
can be as many statements as you want in the false branch. The false branch consists of the statements between the ELSE
statement and the END IF statement.
QUESTION:
In answer to the question, the user enters a 17. What will the new program print?
Answer:
Enter a number
? 17
The number is zero or positive
Positive numbers are > 0
Bye
The TRUE branch was executed because the answer to the question NUMBER >= 0 was TRUE. The true branch consists
of two statements this time.
The condition looks like the part of a DO WHILE condition statement that compares what is held in a variable with other
values. You can use the same comparisons: <, <=, =, and so on.
QUESTION:
Is the following program correct?
PRINT "Enter a Number"
INPUT NUMBER
'
IF NUMBER >= 0 THEN
PRINT "The square root is:", SQR( NUMBER )
ELSE PRINT "There is no square root"
PRINT "Run the program again."
END IF
'
PRINT "Bye"
END
Answer:
No. The ELSE statement must be alone on its line.
QUESTION:
How would you fix the above program?
Answer:
PRINT "Enter a Number"
INPUT NUMBER
'
IF NUMBER >= 0 THEN
PRINT "The square root is:", SQR( NUMBER )
ELSE
PRINT "There is no square root"
PRINT "Run the program again."
END IF
'
PRINT "Bye"
END
In this program there are a different number of statements in the true branch than in the false branch. This is fine.
52 | P a g e