0% found this document useful (0 votes)
3 views47 pages

Introduction Computer Science

The document provides a comprehensive overview of the history and evolution of computers, starting from early counting aids like fingers and stones to advanced fifth generation computers that utilize artificial intelligence. It details the characteristics, definitions, and classifications of computers, including digital, analogue, and hybrid types, as well as their size classifications such as supercomputers and microcomputers. Each generation of computers is described with its key features, technological advancements, and notable examples.

Uploaded by

mubarakjamiu176
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views47 pages

Introduction Computer Science

The document provides a comprehensive overview of the history and evolution of computers, starting from early counting aids like fingers and stones to advanced fifth generation computers that utilize artificial intelligence. It details the characteristics, definitions, and classifications of computers, including digital, analogue, and hybrid types, as well as their size classifications such as supercomputers and microcomputers. Each generation of computers is described with its key features, technological advancements, and notable examples.

Uploaded by

mubarakjamiu176
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CMP 111

INTRODUCTION TO COMPUTER
SCIENCE
DZER, R.M. (MRS.)

FUDMA 2016/2017 SESSION


Page 1 of 47
HISTORY OF COMPUTERS
EARLY AIDS TO COMPUTING

a) Fingers and Toes:

The first early aids of counting were the fingers and toes. Man uses his fingers to help him count, it
was a very simple device which help man to carry out simple additions. But they are not very good
when counting larger numbers more than twenty. So because of this, primitive man started to use
stones instead of fingers to help him count.

b) Stones:

In the early days, when man wants to count say the number of animals he owned, he built a pile of
stones with one stone for every animal. After he had finished building the piles he needed, he then
needed to look at it and see how many there were on the piles he gathered. This method was used
to count larger numbers. The stones could be used to count hundreds of numbers.

c) Abacus:

The next idea was to use coloured beads threaded on a string. At first the beads were made of
stones. Around the year 1200, the Chinese used this method to count. The beads were threaded on
lines of wire frame. The beads on the first line counted the units. The beads on the second wire
counted the hundreds and so on. By moving the beads back and forth along wires, numbers could
be added and subtracted. This device was called an ABACUS. An Abacus is a wooden frame with
strings on which colourful beads are strong, a picture of this is shown below:

Figure 1: Abacus

Page 2 of 47
d) Pascaline

Just over three hundred years ago, the first machines for helping with calculations were invented.
These machines were mechanical. They had parts which moved. The power that caused the
movement was provided by the person who was using the machine. One of these first mechanical
devices was the Pascaline. A Frenchman called Blaise Pascal invented the first machine which could
do both addition and subtraction, in 1642. The machine was named PASCALINE. It had a number
of wheels with teeth on them. The first wheel counted units, the second the tens, the third the
hundreds, and so on.

Every time the first wheel made one complete turn, the second wheel moved one position forward.
Ten turns on the first wheel caused on complete turn on the second wheel. One hundred turns on
the first wheel caused ten turns on the second wheel and one complete turn on the third wheel. A
picture of the machine is shown in figure 2.2 below.

After a large number of turns, by looking at the position of each wheel you can read a number from
them. This method is still used today in fuel and electricity meters; addition is done by moving the
wheels forward, subtraction by moving them backwards.

Figure 2: The Pascaline

e) The Stepped Reckoner

The next step was to invent a machine called the Stepped Reckoner which was able to do
multiplication and division. It could also calculate square roots. This was done in 1671 by a German
called Gottfried von Leibnitz. This machine also used wheels with teeth on them. The nineteenth
century started with the idea of information processing which over rode the previous machine
that can only do subtraction, addition, multiplication and division.
Page 3 of 47
Information processing started with the Stepped Reckoner, the diagram of a Stepped Reckoner is
shown below:

Figure 3: The Stepped Reckoner

JACQUARD’S LOOM

An early example of a machine which processed information was used by a French cloth
manufacturer, called Joseph Jacquard. In 1802 he built a machine to help weave complicated
patterns. When a pattern is woven, each of a number of threads must be raised or lowered. When
this has been done the weaving loom pulls another thread between the raised and lowered threads.
Then each of the threads is raised or lowered in a different way and the loom passes between them
again. This is done very many times when a length of cloth is woven.

Jacquard’s loom used lines of holes on a card to represent the weaving pattern. If there were ten
threads there was space in each line for ten holes. The card was attached to a device on the loom
which was able to look for holes in the card. The device looked at each line. If there was a hole in
positions 3, 4, and 9 then the third, fifth and ninth threads were raised and the rest lowered. After
this was done the loom would start to weave. Then the device would look at the next line of holes
on the card. It would raise and lower the threads and start weaving again. The information on the
card was processed by the loom. A loom operator used to do these before the invention and it was
a tedious and time consuming job. The Jacquard’s loom is show in figure 4 below.

The Jacquard’s loom invention emphasized three concepts:

That information could be coded on punched cards, cards are linked in a series of instructions and
programs could automate jobs.

Page 4 of 47
GENERATION OF COMPUTERS

First Generation Computers

The period of first generation was 1946-1953. The computers of first generation used vacuum
tubes as the basic components for memory and circuitry for CPU (Central Processing Unit). These
tubes, like electric bulbs, produced a lot of heat and were prone to frequent fusing of the
installations, therefore, were very expensive and could be afforded only by very large organizations.
In this generation mainly batch processing operating systems were used. Punched cards, paper
tape, and magnetic tape were used as input and output devices. The computers in this generation
used machine code (binary digits) as programming language.

The main features and characteristics of first generation are:

 Vacuum tube technology


 Supported machine language only
 Slow input and output devices
 Huge size
 Very costly
 Unreliable
 Non-portable
 Consumed lot of electricity
 Generated lot of heat

Some computers of this generation were: ENIAC, EDVAC, UNIVAC, IBM-701, IBM-650

Figure 4: First Generation Computer

Page 5 of 47
Second Generation Computers

The period of second generation was 1956-1963. In this generation transistors were used for
processing. They were cheaper, consumed less power, more compact in size, more reliable and
faster than the first generation machines made of vacuum tubes. Magnetic cores were used as
primary memory and magnetic tape and magnetic disks as secondary storage devices. In this
generation assembly language and high-level programming languages like FORTRAN, COBOL were
used. The computers used batch processing and multiprogramming operating system.

The main features and characteristics of second generation are:

 Use of transistors
 Reliable in comparison to first generation computers
 Smaller size as compared to first generation computers
 Generated less heat as compared to first generation computers
 Consumed less electricity as compared to first generation computers
 Faster than first generation computers
 Still very costly
 Supported machine and assembly languages
Some computers of this generation were: IBM 1620, IBM 7094, CDC 1604, CDC 3600, UNIVAC
1108

Figure 5: Second Generation Computer

Third Generation Computers

The period of third generation was 1964-1971. The computers of third generation used integrated
circuits (IC's) in place of transistors. A single IC has many transistors, resistors and capacitors along
Page 6 of 47
with the associated circuitry. The IC was invented by Jack Kilby. This development made computers
smaller in size, reliable and efficient. In this generation remote processing, time-sharing, multi-
programming operating system were used. High-level languages (FORTRAN-II TO IV, COBOL,
PASCAL PL/1, BASIC, ALGOL-68 etc.) were used during this generation.

The main features and characteristics of third generation are:

 IC used
 More reliable in comparison to previous two generations
 Smaller size
 Generated less heat
 Faster
 Lesser maintenance
 Still costly
 Consumed lesser electricity
 Supported more high-level languages
Some computers of this generation were: IBM-360 series, Honeywell-6000 series, PDP (Personal
Data Processor), IBM-370/168, TDC-316

Figure 6: Third Generation Computers

Fourth Generation Computers

The period of fourth generation was 1971 till date (not completely phased out). The computers of
fourth generation use Very Large Scale Integrated (VLSI) circuits. VLSI circuits having about 5000
transistors and other circuit elements and their associated circuits on a single chip make it possible
to have microcomputers of fourth generation. Fourth generation computers became more powerful,
compact, reliable, and affordable. As a result, it gave rise to personal computer (PC) revolution. In

Page 7 of 47
this generation time sharing, real time, networks, distributed operating system are used. All the
high-level languages like C, C++, DBASE etc., are used in this generation.

The main features and characteristics of fourth generation are:

 VLSI technology used


 Portable and reliable
 Use of PC's
 Very small size
 Pipeline processing
 Concept of internet was introduced
 Great developments in the fields of networks
 Computers became easily available
Some computers of this generation are: DEC 10, STAR 1000, PDP 11, CRAY-1(Super Computer),
CRAY-X-MP(Super Computer)

Figure 7: Fourth Generation Computer

Fifth Generation Computers

The period of fifth generation is 1980-till date. In the fifth generation, the VLSI technology became
ULSI (Ultra Large Scale Integration) technology, resulting in the production of microprocessor chips
having ten million electronic components. This generation is based on parallel processing hardware
and AI (Artificial Intelligence) software. AI is an emerging branch in computer science, which
interprets means and method of making computers think like human beings. All the high-level
languages like C and C++, Java, .Net etc., are used in this generation. AI includes Robotics, Neural
Networks, Game Playing, Development of expert systems to make decisions in real life situations
and Natural language understanding and generation.

The main features and characteristics of fifth generation are:

Page 8 of 47
 ULSI technology
 Development of true artificial intelligence
 Development of Natural language processing
 Advancement in Parallel Processing
 Advancement in Superconductor technology
 More user friendly interfaces with multimedia features
 Availability of very powerful and compact computers at cheaper rates
Some computer types of this generation are: Desktop, Laptop, NoteBook, UltraBook, Ipad, Ipod etc.

Figure 8: Fifth Generation Computer

DEFINITION AND MEANING OF COMPUTERS

A computer is an electronic device, use for manipulating data according to a list of instructions. A
computer is a machine that is used to process data. In a more formal definition, a computer is
any machine or device which, under the control of a stored program, can accept data in
a prescribed form, process the data, and supply the results as information in a specified
form.

There are three points to note about the above definition, that:

Computer is a machine: It consists of electronic and electro mechanical parts working together,
to process data. These machine parts are referred to as computer hardware.

Computer processes data: Essentially, a computer processes data, automatically. It performs


three major functions, which include accepting data, often referred as input, processes data and
supplies these data or information which is referred to as output.

Computer is controlled by a stored program: A program is a set of instructions which tells the
computer what to do. The general term used to describe computer programs is software, in
Page 9 of 47
contrast to hardware. A program is normally stored in the computer’s memory while the instructions
are being carried out. Professionals trained in the art of instructing the computer to solve problems
normally write these programs. The manufacturers permanently fix some programs, called
firmware, into the computers. Software can be placed in the computer’s memory, used, taken out,
and re-used again whenever required.

When a computer is used, data must be presented to it in a prescribed form. This called data
input format. The form, in which data is supplied to the computer, is that in which the program to
be used by the computer is expecting it. A computer program is also used to determine the format
in which the results are to be supplied.

CHARACTERISTICS OF COMPUTERS

The computer has some distinguishing characteristics that make it different form the tools
mentioned above. Such characteristics include:

a) Speed: Ability to process at very fast rate and accurately. The computer is faster than
machines such as the adding machine, slide rule, cash register, calculators, etc.
b) Capacity: Ability to store and process large amounts of data than all the other machines
that processes information.
c) Versatility: The computer can be used for many things, it can be used for all the things the
other information processing tools can be used for, such as addition, subtraction,
multiplication, division etc. It can also be used for the many other things these information
processing tools cannot do, such as processing of examination results and keeping of
student’s records.
d) Programmability: The computer as the ability to be instructed on how to solve a given
problem using programming languages like BASIC, FORTRAN etc.

TYPES OF COMPUTERS

The following factors are used in classifying computers: size of its internal memory, processing
capability, price range and speed/mode of operation.
Page 10 of 47
Based on the way they operate, Computers can be classified into three. They are:

a) Digital computers
b) Analogue computers and
c) Hybrid computers

a) Digital Computers

The word, “digital”, as used here, means whole numbers (discrete); for example, the channel
selector on the television set is a digital device because it restricts you to discrete set of channels;
one cannot select channel 3.123. Another example is the digital wristwatch, which shows you the
exact time in digits. Digital computers are the most common computers. They operate by being
given a series of steps of instructions. Some examples of digital computers are IBM 360/370, PDP
11/34. Digital computers are used in offices and schools.

b) Analogue Computers

Analogue devices have continuous values. For example, the volume control on our television set is
an analogue device, because it allows us to adjust the volume continuously in one smooth
continuous action. Other examples of analogue devices are thermometers, speedometers, and
petrol dispensers at the petrol station, they operate in one smooth continuous form. Analogue
computers operate by accepting data as a quantity varying over a length of time. They are mostly
used in industrial operations.

c) Hybrid Computers

These combine some of the properties of both digital and analogue. For example, setting
(programming) on a modern day television set involves both digital and analogue. You first select
the channel (digital), then you tune the channel until it receives the station you want clearly
(analogue); the station is then stored on that channel (digital). This is an example of a hybrid
device; it involves different processes that combine both the properties of analogue and digital.
Hybrid computers are not too common; they operate in a programmed form and combine the
properties of analogue and digital. An example is a robot used in an industrial environment. The
robot first allows the process to get to a particular temperature (analogue); it then does some other
processes, which is either digital or analogue.

Classification of computers according to their sizes includes:

a) Supercomputers
Page 11 of 47
b) Mainframes
c) Minicomputers
d) Microcomputers

a) Supercomputers:

These are the largest, fastest and most expensive computers. The cost is several millions of dollars,
and the speed is between 600 million to 900 million instructions per second (MIPS). Scientists in
weather forecasting, oil exploration, etc. Use these for complex calculations. Examples of
supercomputers are CRAY X-MP and CRAY 2, which cost millions.

b) Mainframes:

A mainframe computer is a large computer in terms of price, size of internal memory and speed.
Mainframe manufacturers tend to make a “family” or a range of computers, rather than a single
computer, in much the same way as a car manufacturer produces a range of different cars. A
mainframe also cost millions of dollars. It also has a variety of peripheral devices such as printers,
plotters, terminals, etc. more than are found with small computers, and a large amount of external
storage. Mainframe computers usually need a specialized environment in which to operate: with
dust, temperature and humidity carefully controlled. The size of the internal memory is usually
more than 256 megabytes of storage. They are used mostly in large establishments (e.g.
universities, banks, commercial houses, etc.). Examples of mainframes are IBM 360/370 systems,
NCR V-8800 system.

c) Minicomputers:

Minicomputers were developed in the 1970s for specialised tasks (i.e. they are special purpose
computers). They are smaller and less powerful and less expensive than mainframes. Minis, as they
are often called, are easier to install and operate and they require less floor space. Minicomputers
do not require specialised environment to operate in, but care must always be taken to ward off
dust from the equipment. They cost between $15,000 and $200,000. Internal storage capacity of a
minicomputer is usually between 128 megabytes and 256 megabytes. Examples include VAX
750/6000, HEWLETT PACKARD 3000, PDP 11 and so on.

d) Microcomputers:

A microcomputer is a computer whose central processing unit (CPU) is based on the


microprocessor. Microcomputers are at present the most popular of computers. They are very small
(desktop to briefcase size). The capability is generally not as many and not as complex as minis or
Page 12 of 47
mainframes. They are easy to use. They can be linked with mainframes and minis, and their
capabilities are gradually approaching those of minicomputers. Most microcomputers today
generally have between 16 and 128 megabytes. The price ranges from about $400 to over $5,000.
Examples include IBM PC and its compatible, Apple Macintosh, etc. They are often called PC’s.
There are very different kinds of microcomputer. All of them have a keyboard, which looks like the
keyboard of a typewriter. They also have a screen of a television set.

FUNCTIONAL OVERVIEW AND COMPONENTS OF A COMPUTER

Computers are made up of many components which must interact with one another to have a
functional system. The components of a computer are classified into hardware and software. The
hardware refers to the physical parts which can be touched and felt. The software is the various
programs (or instructions) that tell the computer how to perform its tasks.

A functional view of the computer looks at the basic functions that a computer can perform which
are categorized as: Data Processing, Data Storage (long-term or short, temporary storage), Data
Movement, Input/Output (when data are received from or delivered to a peripheral, a device
connected directly to the computer), Data Communications (when data is moved over longer
distances, to or from a remote device), Control of these functions, by instructions provided by the
user of the computer (i.e. their programs).

Computer components that carry out the functions outlined can be divided into the following
categories:

(a) Microprocessors – process instructions and perform calculations.


(b) Storage devices (memory and disks) – hold data.
(c) Input devices (mouse and keyboard) – let the user enter data.
(d) Output devices (monitor, speakers, and printer) – display data.
(e) Network devices (network card and modem) – allow computers to transfer data to and from
other computers.
(f) System Buses -Interconnecting Basic Components
(g) Computer Program

The Computer Hardware

Motherboard: A motherboard or system board is a large printed circuit board with connections for
all the other components in the computer. The motherboard allows the components to exchange
Page 13 of 47
data. It also houses the power supply. The type of motherboard determines the types of CPU,
memory, and hard disk and other peripherals that can be installed in the computer.

System Case: the motherboard and other internal components is housed within a protective case,
usually made of metal and plastic and often referred to as the “box’’. The design of the case can
affect how many expansion cards and components can be added to the computer. Some cases are
designed to be easy to open and access to make maintenance of the computer simpler.

Ports: A hardware port is a socket designed to allow the connection of extra devices, often outside
the system case. Such devices are referred to as peripherals (examples: mouse, keyboard, monitor
and printer). Ports used to connect newest generation of USB memory devices are often referred to
as slots. Ports and connecting cables are always of two genders: male connectors have pins; female
connectors have holes. There are many different types of ports, each requiring a different type of
connector.

Central Processing Unit (CPU): The CPU is an advanced microprocessor. It is the part of the
computer that processes and calculates data. You can think of the CPU as the brains of the
computer. It is made up of the Control Unit (CU), Arithmetic and Logic Unit (ALU) and Main Memory
(or Primary Memory, or Random Access Memory (RAM)).

The CU directs and coordinates all hardware operations in the computer. It is connected by a bus
(collection of wires) to every other hardware component, and through this bus, it sends signal
which are used to control these devices.

The ALU performs all the necessary arithmetic operations (e.g. +, -, *, /) and logical operations
such as comparing two values (e.g. >, <, ≠, ≤, ≥)

The RAM is where data to be processed is being held. Data that come from the input device is first
moved to the RAM. Information is also transferred from RAM to an output device where it then
displayed. The characteristics of RAM are: expensiveness, small in size, fast, volatile, holds the data
that is currently being processed, and its contents can be erased when necessary.

Input device: An input device is any device that is used to transfer data and instructions into the
computer. Examples include keyboard, mouse, joystick, scanner, digital camera, light pen, bar code
reader, touch pad, trackball, graphics tablets, webcam and touch screen.

Output devices: Output devices display information from the computer to the user. The main
output devices display data on screen, print data on paper and play data as sound. Examples
include monitor, printer, speaker, plotter, touch screen, digital or video projector.
Page 14 of 47
Auxiliary Storage (Secondary Storage) devices: Secondary storage devices store large
amount of data for future use. Examples include floppy disk, hard disk, flash drive, Compact Disk
Read Only Memory (CD ROM). The characteristics of auxiliary storage devices are: cheapness, large
in size, slow, non – volatile, used to store data for future use, its contents can be erased when
necessary (read/write memory like RAM).

Read Only Memory (ROM): Read Only Memory stores instructions that are needed by the
computer during start up. The instruction in ROM cannot be erased hence it is termed ‘read only’.

Main Memory (Random Access Memory): Main memory is a place to temporarily store both
instructions (data interpreted as codes for generating control signals) and data upon which
computations are performed.

System Buses: A system bus is a shared transmission medium which is used to connect major
computer components (CPU, memory, I/O).

OVERVIEW OF PROGRAMMING

Programming can be defined as the practice of designing, coding, testing and implementing
program codes intended or tailored to solve a desired task (problem). Our use of the computer
obviously is limited by the nature and type of software and packages available, besides this fact,
even when the appropriate package is available it may not completely meet our specific demand.
Hence one can then write (develop) his or her own program (software) to satisfy his or her peculiar
problems as a result, programming is indispensable especially among professionals.

Computer program

A computer program is a set of instructions that tell a computer exactly what to do. The instructions
might tell the computer to add up or set of numbers or compute two Numbers and make a decision
based on the result or whatever. But a computer program is simply a set of instructions. The
computer follow your instructions exactly and in the process does something useful like generating
an employee payroll or display a game on the screen or implementing a word process.

A programming language is an artificial language designed to communicate instructions to a


machine, particularly a computer. Programming languages can be used to create programs that
control the behavior of a machine and/or to express algorithms precisely.

The functions of a computer system are controlled by computer programs; a computer program is a
clear, step-by-step, finite set of instructions. A computer program must be clear so that only one

Page 15 of 47
meaning can be derived from it. A computer program is written in a computer language called a
programming language.

STAGES OF PROGRAM DEVELOPMENT (Programming Process)

Before a computer program is successfully written, it must have passed through the following
stages:

(a) Problem Definition:

The first stage is to define the problem that prompted the search for a programmed solution. No
one solves a problem he does not understand. The problem to be solved by computer should be
well stated and understood before the solution will be worked out.

Knowing the objective is the first consideration. Is it a payroll or editing program? Knowing who the
end user will be is also important. Determining the inputs and outputs is next. How will the program
operate and what data is needed to make it happen. After this has been decided, feasibility is the
next consideration. How many programmers will it takes, is the project within budget, does the
project have a realistic outlines, finally, if the project is good, then one must take measures to
ensure the project is properly documented and analyzed.

Five mini steps are considered in problem definition:

i. Clarify objectives and users


ii. Clarify desired output
iii. Clarify desired input
iv. Clarify desired processing
v. Double check the feasibility of implementing the program.

(b) Development of algorithm:

An algorithm is set of well-defined rules for solving a problem in a finite number of steps or simply
a description of the step by step method of solving a problem. Each step in the algorithm must be
made perfectly clear and void of assumption or vague ideas. It must contain a finite or limited
number of operations. It should be able to provide output in order to know the result of
implementing the procedures. It should have an existing point where the operation ends.

Examples of Algorithms

A. An algorithm to add two numbers:


Page 16 of 47
Step 1: Start
Step 2: Output “To add 2 numbers”
Step 3: Output “Enter 2 numbers”
Step 4: Input num1, num2
Step 5: Add num1 and num2 and assign the result to sum
OR sum num1 + num2
Step 6: Output sum
Step 7: Stop

B. An algorithm to compute and print out the average of three numbers a, b, c:

Step 1: Start
Step 2: Output “To compute sum and average of 3 numbers”
Step 3: Output “Enter 3 numbers”
Step 4: Input a, b, c
Step 5: Compute sum = a+ b + c
Step 6: Compute average = sum divided by 3 OR sum/3
Step 7: Output average
Step 8: Stop

C. An Algorithm to calculate the largest of 3 numbers using if only:

Step 1: Start
Step 2: Output ”To calculate the largest of 3 numbers”
Step 3: Output “Enter the 3 numbers”
Step 4: Input a,b,c
Step 5: If a>b and a>c
Step 6: Output a “is the largest”
Step 7: If b>a and b>c
Step 8: Output b “is the largest”
Step 9: If c>a and c>b
Step 10: Output c “is the largest”
Step 11: Stop

D. An algorithm to compute managers commission given that commission is 10% of sales


provided sales is greater than N50,000 otherwise no commission is given:

Step 1: Start
Step 2: Output “Computing Manager’s Commission”
Page 17 of 47
Step 3: Output “Enter the sales figure”
Step 4: Input sales
Step 5: If sales>50000
Step 6: Compute comm=10/100 multiplied by sales
Step 7: Else
Step 8: Comm=0
Step 9: Output comm
Step 10: Stop

E. Algorithm to compute the average score of 30 students

Step 1: Start
Step 2: Output “Average score of 30 students”
Step 3: Output “Enter the scores of 30 students”
Step 4: sum = 0
Step 5: for i=1 to 30
Step 6: input score
Step 7: Compute sum=sum+score
Step 8: Repeat step 5 to step 7
Step 9: Average=sum/30
Step 10: Output Average
Step 11: Stop

Exercises

1. Write an algorithm to calculate the area of a circle with radius r.


2. Write an algorithm that will find the roots of a quadratic equation ax²+bx+c=0.
3. Write an algorithm to find the larger of two numbers.
4. Write an algorithm that will accept any number and determine whether the number is odd or
even.
5. Write an algorithm that will accept an integer and check whether it is positive or negative or
zero.

(c) Flowcharting

An algorithm can be converted into either a written form or pictorial form, or both. The written form
is called the pseudo code, and the pictorial form is a FLOWCHART. The flowchart is thus a pictorial
representation of an algorithm. It helps the programmer in planning the sequence of operations
involved in a program before actually writing the program in a programming language.
Page 18 of 47
A flow chart illustrates a process graphically using a set of standard symbols, the shape of each of
which indicates the operation being described. Thus, the flow chart acts as a visual aid for
programming. Each symbol represents an operation and has a specified geometrical shape joined
together by means of arrows. The arrows indicate the flow of logic. Each box contains outlines of
the steps to be executed by the computer at each stage. Below are some of the flowcharting
symbols commonly used in expressing the logic of programs.

Input / Output

Processing

Decision

For Loop

On-page connector

Directional Arrows

Page 19 of 47
Examples of flowcharts

1. A flowchart to compute and print out the averages of three numbers a, b, c,


start

a,b,c

Sum=a+b+c

Average=sum/3

average

stop

2. A Flowchart to compute managers commission giving that commission is 10% of sales


provided sales is > N500000, otherwise, no commission is given.

(d) Code the program


After the problem has been analyzed it must be coded or written using the desired programming
Page 20 of 47
language. Once the appropriate programming language has been chosen, it is imperative that the
programmer follow the syntax rules of the programming language.
Two mini steps:
 Select the appropriate high-level programming language

 Code the program in that language following the syntax carefully

(e) Testing and Documentation

The essence of program testing also referred to as program validation is to determine whether
any error still remains in the program. Testing is the process of running the computer program
and evaluating the program results in order to determine if any errors exist. The testing is done
by running the program with various sets of inputs values so as to be sure that the expected
result is gotten.

Documentation is the description of the program in the proper form for users and to enhance
maintainability. It describes the working of a program and how expected problems could be
solved. Documenting a program is very important because it aids the users in understanding the
program better and it also aids maintenance of such program. The documentation may be
internal – in the form of comments which exist within the program, or may be external in the
form of a written description and structured diagrams.

INTRODUCTION TO BASIC PROGRAMMING

In computer programming, BASIC (an acronym for Beginner's All-purpose Symbolic


Instruction Code is a family of high-level programming languages.

The original BASIC was design in 1964, by John George Kemeny and Thomas Eugene Kurtz at
Dartmouth College to provide access for non-science students to computers. At the time, nearly all
use of computers required writing custom software, which was something only scientists and
mathematicians can do. The language (in one variant or another) became widespread on
microcomputers in the late 1970s and home computers in the 1980s. BASIC remains popular to this
Page 21 of 47
day in a handful of highly modified dialects and new languages based on BASIC such as Microsoft
Visual Basic.

The design principles of BASIC were:

1. Easy for beginners to use.


2. A general-purpose programming language.
3. Allow advanced features to be added for experts (while keeping the language simple for
beginners).
4. It is interactive.
5. Provide clear and friendly error messages.
6. Respond quickly for small programs.
7. Not to require an understanding of computer hardware.
BASIC CHARACTER SETS

While learning a natural language, we normally start from its alphabets which are called characters.
These characters are broadly classified into three categories viz Alphabetic, Numeric and special
characters:

(a) Alphabetic characters are the 26 alphabetic characters (A, B, C, … Z)


(b) Numeric characters are the 10 numeric characters ( 0 1 2 3 4 5 6 7 8 9)
(c) Special characters are (+ - * / + = , . ( ) “ & $ ? etc )

TYPES OF OPERATORS

BASIC has three classes of operators:

(a) Arithmetic operators


(b) Relational operators
(c) Logical operators

Arithmetic operators: are those operators which permit arithmetic/mathematical


operations/calculations to be performed on any given data (operand), they include +, -, *, /, **,
^.

+ Addition
- Subtraction
* Multiplication
/ Division
Page 22 of 47
** or ^ Exponentiation

Relational operators: are those operators which allow for comparison. Below are some
relational operators in BASIC and their meanings

Operator meaning
> Greater than
< Less than
= Equal to
>= Greater than or equal to
<= Less than or equal to
<> Not equal to

Logical operators

These are operators which allow for a selection based on one or more conditions being true or
false. These operators include OR, AND and NOT

Example: IF A = 1 OR B = 2 THEN PRINT “TRUE” A < B AND A< C THEN PRINT “LAST = A” DATA
TYPES

BASIC programming language uses two types of data:-

(a) Numeric data types eg 10, 20, 330.50, 2.5


(b) Alphanumeric/String data eg “gina” “ P. o. Box 2041”

All data is represented in the computer in binary form. The type of data determines the way in
which it is represented and the operations which may be performed on it. Data is usually referred
to as variables.
In programming, a variable is a value (data) that can change, depending on conditions or on
information passed to the program. Typically, a program consists of instructions that tell the
computer what to do and data that the program uses when it is running. The data usually consists
of constants or fixed values that never change and variable values (which are usually initialized

Page 23 of 47
to "0" or some default value because the actual values will be supplied by a program's user).
Usually, both constants and variables are defined as certain data types.

Reserved words (occasionally called Keywords) are special words reserved by a programming
language or by a program. You are not allowed to use reserved words as variable names. For
example, in BASIC the words Print, Remark, Input, Locate, Data, etc are reserved because they
have special meaning.

A variable is usually represented with a unique name which is called variable name. Program
applies such a name to memory and uses it to refer to it. A variable name usually consists of
alphabetic characters and decimal digits, beginning with an alphabetic character. It is usually good
to give meaningful names to your variables. Examples: VOL, TEMP, A2, COLUMN, IBM370
etc. Names are given to memory locations for easy referencing. A variable name in BASIC consists
of 1 to 40 characters. The string variable name always have dollar ($) sign attached to it as the last
[Link] name$. It cannot be used in a formula during computation. The numeric variable can
be used in computation, it does not have dollar sign ($) attached to it. E.g. Length, amount, price.
It is advisable to give meaningful name to your variable. Reserved words should not be used in
forming variable names.

Rules for forming variable names in summary

(a) All variable names must start with a letter of the alphabet from A to Z.
(b) No special symbols or basic key words must be used as variable name.
(c) If more than one variable is used in a computer program, each variable name must be
different.
(d) Keep names short and meaningful as to their use.
(e) Variable names should help you remember what they hold. Good examples: age, salary,
name, weight etc. Bad examples: a, b, c, x, y, z.
(f) The variable type or usage must be declared or specified by:
i. Use a name (with no special symbol) for a NUMERIC location.
ii. Use a name with a $ sign at the end for an ALPHANUMERIC location.

Rules for writing Basic Programs

(a) It must start with a line number ( number statement)


(b) Two statements can be combined in a line, but should be separated by comma
(c) BASIC statements should always follow the number statement
(d) Succeeding lines must be greater than the preceding lines

Page 24 of 47
(e) Numbers must be whole numbers
(f) No repetition of number statement
(g) There should be at least a space between the number statement and BASIC statement
(h) A full stop is no allowed at the end of any statement the keyboard when the program
(i) The program must always stop with an END statement.

Basic Statements

(a) The REM statement

REM: means remark to basic interpreter. It is used to indicate comment line. In a program. It
can be replaced with a quote mark. Example:

10 Rem to sum three numbers 10 „To Sum Three Numbers

(b) INPUT Statement

It is used to ask for input (data) through the keyboard when the program is running. It is used for
interactive programming. INPUT Statement is followed by variable name, more than one variable
name can declared with an input statement but should be separated by comma. When running the
program the data should also be typed separated by comma as declared in the INPUT statement.
E.g.

INPUT AMT, NAME$, discount

(c) THE READ AND DATA Statement

This is another Statement used to ask for input (data), but this time the data is not expected from
the keyboard but within the program. When the BASIC interpreter encounters a READ statement, it
looks for the DATA statement which contains the actual data for the variables declared in the READ
statement. The data statement must be used anytime the READ statement is used. The DATA
statement must match with the READ statement variables declared.

e.g. READ NAME$, AMT

__

DATA ”Bag “, 30000

(d) THE PRINT Statement

Page 25 of 47
This is an output statement, it is used to tell the computer to return to us or show us the results
from computation on the screen. Example: 10 PRINT A.

Where A is a variable name, more than one item may be listed in the print statements but they
must be separated by commas or semicolons.

Example of BASIC programs using the above statements

1. A program to calculate the area of a room Solution

10 REM A PROGRAM TO CALCULATE THE AREA OF A ROOM

20 INPUT “ENTER THE LENGTH”; LENGTH

30 INPUT “ENTER THE WIDTH”; WIDTH

40 LET AREA = LENGTH * WIDTH

50 PRINT “THE AREA OF THE ROOM IS”; AREA

60 END

2. To rewrite the program using the READ/DATA Statement Solution

10 REM A PROGRAM TO CALCULATE THE AREA OF A ROOM

20 READ LENGTH, WIDTH

30 LET AREA = LENGTH * WIDTH

40 DATA 100, 50

50 PRINT “THE AREA OF THE ROOM IS”; AREA; “M2”

60 END

(e) LET STATEMENT: The LET statement is used for assignments. The LET statement operates
from right to left. That is to say, the value on the right of the equal sign is assigned to the
variable on the left of the equal sign. The sign means an assignment and not equality.
Example

let PI = 3.142, let sum = A + B + C


Page 26 of 47
1. Program that accept three numbers (A, B, C), compare them and print the largest.

Solution

10 REM A PROGRAM THAT ACCEPTS THREE NUMBERS COMPARE THEM AND PRINT THE
LARGEST
20 INPUT “ENTER THE NUMBERS “; A, B, C
30 IF A > B THEN BIGGER = A
40 ELSE BIGGER = B
50 IF BIGGER > C THEN BIGGEST = BIGGER
60 LSE BIGGEST = C
70 PRINT BIGGEST
80 END
(f) GOTO STATEMENT: is used to transfer execution to a specified line number. Example GOTO
20- this tells the computer to continue execution from line 20.

(g) IF – THEN – ELSE STATEMENT: This statement is used to test whether a transfer of control
or execution will take place or not. It is a powerful statement that gives the computer the
ability to make decisions and take and alternative action based on the outcome. It is always
used in conjunction with relational operators to set the condition that will be tested.
1. A program that will read in the marks scored by a student in six different courses and
calculate the average score.

Solution

10 I = 0.0
20 SUM = 0.0
30 INPUT SCORE
40 I = I +1
50 SUM = SUM + SCORE
60 IF I <= 5 THEN GOTO 3O
70 AVERAGE = SUM/6
80 PRINT AVERAGE
90 END
NOTE: the ELSE statement is not mentioned in the above program, but line 70 is by default the
implied ELSE statement because it is only executed when line 60 is no longer true.

(h) DIM STATEMENT

Page 27 of 47
This statement is used for declaration of array or matrix, it must be the first statement to be coded
before any statement that reference that array or matrix. Array can be single dimensional or double
dimensional.

Example:

DIM A(10)- This is a single dimensional array with 10 elements.

DIM B(5,4) – This is a double dimensional array or matrix named B with 5 rows and 4 columns
given a total of 20 ( i.e. 5 * 4) elements in the array.

1. A program that will read in 20 elements of an array c alled A, and calculate


their average.
average.
Solution
10 DIM A(20)
20 FOR I = 1TO 20
30 INPUT A( I )
40 SUM = SUM + A(I)
50 NEXT I
60 AVERAGE = SUM/20
70 PRINT AVERAGE
80 END
2. A program to read and print the elements of a 3 x 4 matrix.
Solution
10 DIM A (3,4)
20 I = I + 1
30 J = J + 1
40 INPUT A(I,J)
50 PRINT A(I,J)
60 IF J <= 4 THEN GOTO 30
70 J = 0
80 IF I <=2 THEN GOTO 20
90 END
Page 28 of 47
(i) CLS STATEMENT:

This is a statement used to clear or tidy up the screen. Example: 10 CLS –This clears the previous
content of the screen or display.

EXPRESSIONS

An expression is a rule which when evaluated will give a single value, in its simplest form it consist
of two operands with an operator between them. In basic there are numeric expression, logical
expression, and string expression.

NUMERIC EXPRESSION:- to understand numeric expression let us look at arithmetic operators,


arithmetic operators are used to indicate arithmetic operation such as addition, subtraction,
division, multiplication and exponentiation.

ARITHMETIC OPERATORS

Addition: + (Plus sign)


Subtraction: - (Minus sign)

Division: / (Slash)
Exponentiation: ^ (Caret , or Upward-pointing arrow)

Therefore, these arithmetic operators are used to connect numeric constants and numeric
variables to form Numeric expression.

Examples of numeric expressions are:

A+B+C-D A+B (5*P–2*Q)/(X+Y)

COUNT + 1 3.142 * R ^ 2 4 * PI * RADIUS ^ 3 / 3

Many versions of BASIC include two additional arithmetic operators: integer division (\) and integer
remainder (MOD). In integer division, each of the two given numbers is first rounded to an integer;
the division is then carried out on the rounded values and the resulting quotient is truncated to an
integer. The integer remainder operation provides the remainder resulting from an integer division”.

Examples

13 / 5 = 2.6 13 \ 5 = 2 13 MOD 5 = 3
Page 29 of 47
8.6 / 2.7 = 3.185185 8.6 \ 2.7 = 3 8.6 MOD 2.7 =0

8.3 / 2.7 = 3.074074 8.3 \ 2.7 =2 8.3 MOD 2.7 = 2

HIERACHY OF OPERATIONS

There are some situations when several operators appear in an expression, to solve these
problems we therefore apply hierarchy of operations rule. The hierarchy of operations is:

i. Exponentiation: all exponentiation operations are performed first.

ii. Multiplication and division: they have the same hierarchy, it means any one that comes first
will be evaluated before the other one, but they are performed after exponentiation.

iii. Integer division: in those version of BASIC that include this operation, integer division
operations are carried out after all multiplication and (ordinary) division operations.

iv. Integer remainder: in those version of BASIC that include this operation, integer

v. remainder operations are carried out after all integer divisions operations.

vi. Addition and subtraction:-they have the same hierarchy but all the above operations must be
performed first.

USE OF PARENTHESES

It is possible to change the normal hierarchy of operations in a numeric expression. This is easily
done by inserting pairs of parentheses at the proper place within the expression.

The operation within the inner most pair parentheses will be performed first followed by the
operations within the second innermost pair of parentheses and so on.

Note: you have to make sure that the left and right parentheses balance.

Example

Evaluate the algebraic term [ 2 ( a + b ) 2 + ( 3c ) 2 ] m ( n+1 ) into BASIC equivalent.

Solution

(2 * ( a + b )^ 2 + (3 * c)^ 2 ) ^(m / (n+1 ))


Page 30 of 47
Or both expressions are correct

(( 2 * (( a + b ) ^ 2 )) + (( 3 * c ) ^2 )) ^ ( m / n + 1))

SPECIAL RULES OF NUMERIC EXPRESSION

Sometimes special problems can arise if an expression is not correctly written. It is possible to avoid
such problems if the following rules are applied.

i. Preceding a variable by a minus sign is equivalent to multiplication by -1.

ii. Example –a ^ 2 is equivalent to – ( a ^ 2 ) or – 1* ( a ^ 2).

iii. Except for the first condition described, operations cannot be implied.

iv. Example the algebraic expression 3 ( k1 + 3k2 ) will be written in BASIC as 3 *


( k1 + 3 * k2 ) note that the multiplication must be shown explicitly.

v. In an expression involving exponentiation, a negative quantity can be raised to a power only


if the exponent is an integer. ( do not confuse the exponent in a numeric expression with the
exponent that is part of a floating point constant).

Example:

Consider the expression (P1 + P2) ^ 3 this is correct, because no exponent within parentheses.

( B ^ 2 – 4 * A * C ) ^ 5 it will be valid only if the expression represents a positive quantity within


the parentheses because of the exponent B^ 2.

STRING EXPRESSION

“Numeric operations cannot be performed on string constants or variables. However, most versions
of BASIC allow strings and string variables to be concatenated (i.e combined, behind the other).
The 1987 ANSI standard defines the ampersand (&) as a string concatenation operator though
some versions of BASIC use the plus sign for this purpose.”

A$ = “ ONE ”

B$ = “ BILLION”

Then the string expression

A$ & “ ” & B$ &“ NAIRA ”


Page 31 of 47
Will cause the three individual strings to be concatenated, resulting in the single string. ONE
BILLION NAIRA

In Microsoft BASIC , the string expression would be written as A& + “ ” + B & + “ NAIRA”

CONTROL STRUCTURES

In simple BASIC problem we must have seen that statements were executed in the order in which
they appeared within a program. Each statement is executed once and only once. Program of this
kind do not include any logical control structures. i.e determine if various condition are true or false,
also they do not require that certain groups of statements be executed on selective basis or
executed repeatedly. Therefore conditional execution, looping (conditional and unconditional
looping), selection will be discussed in control structures.

RELATIONAL OPERATORS AND LOGICAL EXPRESSIONS

To carry out conditional branching operations in basic, the following relational operators are used.

RELATIONAL OPERATORS

Equal: = Not equal: <> Less than : < Less than or equal:
<= Greater than: > Greater than or equal: >=

LOGICAL EXPRESSIONS

Logical Expression is an expression which use logical operators to compare numeric quantities ( i.e
constant, numeric variables or numeric expressions) or string that returned either TRUE or FALSE.

Note that the operands within a logical expression must be of the same type i.e both must be
numeric or both must be strings.

Examples

A = 10

Score > 56

X < 14 Logical expression involving Numeric quantities Balance <> 1000

Examples

Name$ = “ AHMED ”

Page 32 of 47
Char$ <> “ M ”

Logical expression involving strings Target$ < City$

Note that the string expressions involving operators <, <=, >, >= refer to alphabetical ordering,
that is these operators are interpreted as” comes before “ or “ comes after ” rather than “ Less than
or greater than “ the actual alphabetic ordering is determined by the system used to encode the
characters ( ASCHI CHARACTER SET).

Upper-case characters precede lower case characters. Blank space precedes nonblank characters,
string comparism carried out on a character by character basis from left to right.

Examples

Car precedes far, LOW preceded low, joy precede joys

LOGICAL OPERATORS

The logical operators in BASIC are AND, OR and NOT. The first two operators ( AND and OR) are
used to combine logical expressions, thus forming more complex logical expression ( from true to
false).

Examples of logical expression that make use of logical operators. A = 25 AND NAME$ = “ Ahmad

Score > 50 OR Score AND Name$ < = “ Ahmad ” Score < 50 OR Score <> 40

Not ( Name$ = “ Ahmad ”) AND ( ACCOUNT$ = “ CURRENT”)

NOTE : there are some versions of BASIC that include additional operators XOR, EQV, IMP. XOR
will result in a condition that is true only if one expression is true and the other is false; EQV will
result in a condition that is true if both expressions have the same logical value (either both true or
both false); IMP will result in a true condition unless the first expression is true and the second is
false.

HIERARCHY OF ARITHMETIC, RELATIONAL AND LOGICAL OPERATORS

Operation Operators
Page 33 of 47
i. Exponent ^

ii. Negation (i.e., preceding a numeric quantity with a minus sign) -

iii. Multiplication and division * /

iv. Integer division \

v. Integer remainder MOD

vi. Additions and subtraction + -

vii. Relationals =< > < < = > >=

viii. Logical NOT NOT

ix. Logical AND AND

x. Logical OR OR

xi. Logical XOR XOR

xii. Logical EQV EQV

xiii. Logical IMP IMP

NOTE that within a given hierarchical group, the operations are carried out from left to right. The
natural hierarchy can be altered by using parentheses as earlier explained in arithmetic expressions.

Example

Consider the logical expression

Balance > 1000 OR order = 1 AND Account$ = “ Saving ” This expression is equivalent to

Balance > 1000 OR ( order = 1 AND Account$ = “ Saving ”)

On the other hand, the logical expression below has a different interpretation. ( Balance > 1000 OR
order = 1 ) AND Account$ = “ Saving ”

The explanation on the above example will be provided in the class.

Page 34 of 47
CONDITIONAL EXECUTION: THE IF – THEN STAEMENT

IF –THEN STATEMENT is used to execute a single statement on a conditional basis. Format/


syntax

IF logical expression (condition) THEN

Executable statement

Note that executable statement will be executed only if the logical expression (condition) is true
otherwise, the statement following IF – THEN will be executed next.

Example 1

If Y >1 then Print Y

Note that print statement will be executed only if the logical expression Y > 1 is true.

Example 2

IF score < = 39 then Let remark = “ Fail ”

Print “ Remark ”; Remark

CONDITIONAL EXECUTION: IF – THEN – ELSE BLOCKS

An IF – THEN – ELSE block permits one of two different groups of executable statement to be
executed on the outcome of logical test. Thus, it permits a much broader form of conditional
execution than is available with a single IF – THEN statement.

The format/syntax:

IF Logical expression THEN

……………………… Executable statements

………………………….

Else

…………………………. Executable statements

………………………….

Page 35 of 47
END IF

If the logical expression is true, then the first group of executable statements will be executed.
Otherwise the second group of executable statements will always be executed.

Example 1

IF X > Y THEN

PRINT Y,” IS GREATER ” ELSE

PRINT X, “ IS GREATER ” END IF

The complete program:

program to find the larger of two numbers.

Solution

10 CLS

20 REM program to find the larger of two numbers 30 INPUT “ Enter X and Y ”; X,Y

40 IF X < Y THEN

50 PRINT X, “ IS GREATER ”

60 ELSE

70 PRINT Y, “ IS GREATER ”

80 END IF

90 END

Example 2

Write a program to calculate either the area of a circle or the area of a rectangle, base on the string
assign to the variable form$.

Solution

CLS

Page 36 of 47
REM program to calculate either area of a circle or rectangle INPUT “ The form ”; Form$

IF ( form$ = “ Circle”) THEN INPUT “ Radius”; r

Let Area = 3.142 * r^2 Else

INPUT “ Length and width ”; L,W Let Area = L* W

END IF

PRINT “ Area = ”; Area

END

Note that IF – THEN block allow a single group of statements to be executed conditionally.

Example

IF Salary >= 30000 THEN

LET Tax = 0.3 * Gpay LET NetP = Gpay – Tax END IF

PRINT “Gross pay =”;Gpay PRINT “ TAXES”; Tax PRINT “ NET PAY”; NetP END

NESTED IF

A more general form of the IF- THEN –ELSE block can be written as

IF Logical expression 1 THEN

…………………………… Executable statements

…………………………..

ELSEIF Logical expression 2 THEN

………………………….. Executable statements

…………………………..

ELSEIF Logical expression n THEN

……………………………..

ELSE
Page 37 of 47
…………………………….

Executable statements

……………………………

ENDIF

Example 1

Write a program to find the roots of the quadratic equation if b^2 - 4ac = 0,b^2 – 4ac < 0, b^2 –
4ac > 0.

Solution

IF b^2 – 4ac = 0 THEN

X= -b/2a

IF (b^2 – 4ac) < 0 THEN

LET Real = -b/2a

LET imag = (4ac-b^2 ) /2a Let X1 = Real + imag

Let X2 = Real - imag

IF ( b^2 – 4ac ) > 0 THEN LET ROOT = (b^2 – 4ac)1/2

Let X1 = ( -b – Root) / 2a Let X2 = (-b - Root) / 2a The complete program CLS

REM Program to calculate the root of a quadratic equation INPUT “ The value of A”; A

INPUT “ The value of B”; B INPUT “ The value of c”; C LET D = (b^2 - 4 *a *c)

IF d > 0 THEN

LET X1 = (-b + SQR(d)) / (2*a)

LET X2 = (-b - SQR(d)) / (2*a)

Print” Real root: X1= ”; X1; “X2=”;X2 ELSEIF

D =0 THEN

Page 38 of 47
Let X = -b / (2 * a)

Print “ Repeated Root: X= ”; X ELSE

LET REAL = -b / (2 * a)

Let Imag = SQR ((-d ) /2*a )

Print “ Complex Roots: X1 = ”; Real; “ + ”; Imag ; Imag; “ I ” Print “X2 = ”; Real; “ – “ Imag; “ I”

END IF

END

REPETITION (LOOPING)

In writing computer program it is often necessary to repeat part of a program number of times.
LOOPING:- this is the process of executing a part or segment of a program several times.
UNCONDITIONAL LOOPING:FOR – NEXT STRUCTURES

The FOR – NEXT Structure is a block of statements that is used to (carryout unconditional looping)
execute a sequence of statement some predetermined number of times. In other word, this is a
deterministic loop that executes a segment of the program for a specified number of times.

Format/syntax

For Variable = Initial value to final value Statement 1 (Executable statements)

………………………………………

Next Variable

The initial value and the final value must be integer.

Variable is an identified whose value begins with initial value, increases by 1 each time the loop is
executed, until it reaches final value. Next variable means the next value for the counter. If the
next value greater than the loop it terminates.

EXAMPLE 1

Write a program to print your name twenty (20) times.

Solution
Page 39 of 47
CLS

REM program to print your name 20 times INPUT “ Enter your name ”; name$

For I = 1 to 20

PRINT “ your name ”; Name$ Next I

END

EXAMPLE 2

Write a program to calculate the average of a list of numbers.

Solution

CLS

REM Program to calculate the average of a list of n numbers INPUT “ Enter how many numbers ”; n

LET Sum = 0

For k = 1 to n PRINT “K = ”; K INPUT “ X = ”; X

LET Average = Sum / n

Print

Print “ Average = ”; Average END

A more general form of the FOR – NEXT STRUCTURE can be written as:

FOR Variable = Initial value to final value STEP X

Executable statements

NEXT variable

Here X determines the amount by which initial value changes from one pass to the next. The
quantity need not be restricted to an integer, and it can be either positive or negative. If X is
negative, then initial value must be greater than final value (because the value assigned to)

Page 40 of 47
The result will be

2.5 2 1.5 1 0.5 0 -0.5 -1

CONDITIONAL LOOPING: DO – LOOP STRUCTURES

A DO – LOOP Structure always begins with a DO statement and end s with a loop statement.
There are four (4) different ways to write a DO – loop structure.

1. DO WHILE …………………. LOOP


2. DO UNTIL…………………..LOOP
3. DO ……………………………LOOP WHILE
4. DO …………………………….LOOP UNTIL

1. DO WHILE…………...LOOP:-this is an underteministic loop that repeats the execution of a vlock


of statements in a program as long as the condition (Logical expression) is true.

General format/format

DO WHILE Logical expression

……………………………….. Executable statements

……………………………..

LOOP

Example

solution

LET Count = 1

Do while Count = 20 PRINT COUNT

LET Count = Count + 1 Loop

2. DO UNTIL ……………….. LOOP:- this is an undeteministic loop that repeats the execution of a
block of statement so far the condition is false.
Page 41 of 47
General form/ format

DO UNTIL Logical expression

……………………………… Executable statements

……………………………..

Loop Example

Let us consider the example given in DO – WHILE …………….loop

Let Count = 1

DO Until Count >20 PRINT Count

Let Count = Count +1

Loop

3. DO ……………LOOP WHILE :-this is a structure that continues to loop as long as the logical
expression is true.

General form/format

DO

………………………. Executable statements

……………………………..

LOOP WHILE LOGICAL EXPRESSION

Example

Let Count = 1 Do

Print Count

LET Count = Count +1 LOOP WHILE Count = 20

4. DO LOOP UNTIL:- this is the structure that loop as long as the logical expression is not true.

Page 42 of 47
General form/format

DO

……………………………. Executable statements

………………………… LOOP UNTIL logical expression Example

Let count = 1

Do

Print Count

Let count = count +1 LOOP UNTIL Count >30

Note: Control can be transferred out of a DO LOOP block using the EXIT DO statement. This
statement is analogues to EXIT FOR, which is used with FOR NEXT blocks.

EXAMPLE

Program to calculate the average of a list of positive number using DO……..LOOP Solution

REM program to calculate the average of a list of positivenumbers

PRINT “TO STOP “enter zero”

LET sum = 0 Let I = 1

PRINT “= “; I; “ X=”; INPUT “X”; X

DO UNTIL X = 0

LET sum = sum+x LET I= I+1

IF sum >= 120 THEN EXIT DO Print “ I= “; I; “ X = “ ;

INPUT X LOOP

LET average = sum / (I - 1) PRINT

PRINT

PRINT“ Average =”; Average END

Page 43 of 47
NESTED CONTROL STRUCTURES

Control structures can be nested (i.e embedded) one within another. The inner and outer control
need not be the same. For example, an IF…..THEN block can be nested within FOR – NEXT
structure or a DO LOOP structure, vice-versa. Example will be given in the class.

SELECT CASE STRUCTURES

This is the structure which allows one of several different groups of statement to be executed,
depending on the value of an expression.

SELECT CASE STRUCTURE format

SELECT CASE expression CASE value 1

Executable statements CASE value 2 Executable statements

……………………….

CASE ELSE

Executable statements END SELECT

Example 1

Write a program that will accept two numbers and display the value of one number to the selected
power.

Solution

REM program to raise Y to a selected power INPUT “Y = ”; Y

INPUT “ X(1, 2 OR 3) = ”; X SELECT CASE X

CASE 1

PRINT “ Y = “ ; Y CASE 2

PRINT “ Y squared = “ ; Y^X CASE 3

PRINT “ Y Cubed = “ ; Y^X CASE ELSE

Page 44 of 47
PRINT “ ERROR –Please try again” END SELECT

END

The expression in the SELECT CASE statement can be a string rather than a numeric expression.
In this case, the values in the subsequent CASE statement must also be strings. The original string
expression will then be compared with the string values in the subsequent CASE statement s until a
match is found.

Example

Write a Program to choose and display string selection of different color. REM program to choose
and string selection of different colour.

INPUT “ Enter Colour ”; cl$ SELECT CASE COLOR$ CASE “RED”

PRINT “Colour is RED”; CASE “GREEN”

PRINT “Colour is GREEN”; CASE “WHITE”

PRINT “Colour IS WHITE”; CASE ELSE

PRINT “ ERROR – please try again” END SELECT

END

APPLICATION OF COMPUTERS

Computers have a large number of applications in variety of fields. Computers have great A
programming language is an artificial language designed to communicate instructions to a machine,
particularly a computer. Programming languages can be used to create programs that control the
behavior of a machine and/or to express algorithms precisely.

The functions of a computer system are controlled by computer programs; a computer program is a
clear, step-by-step, finite set of instructions. A computer program must be clear so that only

Page 45 of 47
one meaning can be derived from it. A computer program is written in a computer language called
a programming language.

applications in the field of Information Technology, Physics, Medical Sciences, Economics, Statistics,
Financial Management, Nuclear Physics, Business, Human Resource Management etc. Computers
are widely used for effective management of information and resources in almost all sectors.

(a) Marketing and advertising agencies rely on computer databases of customers and various
other tools to track the needs of the customers. Human Resource Management Information
Systems help organizations to keep record about the employees. Computers are used in
networks which help individuals in the organizations to communicate with each other by
sharing files and important documents.
(b) Education: One revolution in education is the advent of distance learning. This offers a
variety of internet and video-based online courses. Electronic library has brought a lot of
books within the reach of students.
(c) Health and Medicine: Computer technology is radically changing the tools of medicine.
Computer software exist that assist doctors in diagnosis. Scanning devices are controlled by
embedded computer devices.
(d) Science: Scientists have long been users of computers. A new adventure among scientists is
the idea of “collaboration”, an internet based collaborative laboratory, in which researchers
from where ever around the world can work easily together even at a distance.
(e) Business: Business clearly see the internet as a way to enhance productivity and
competitiveness. Some areas of business that are undergoing rapid changes are sales and
marketing, retailing, banking, stock trading, etc. Sales representatives not only need to be
better educated and more knowledgeable about their customer’s businesses, but also must
be comfortable with computer technology. The internet has become a popular marketing
tool. The world of cyber cash has come to banking – not only smart cards but internet
banking, electronic deposit, bill paying, online stock.
(f) Recreation and Entertainment: Our entertainment and pleasure-time have also been affected
by computerization. For example:
i. In movies, computer generated graphics give freedom to designers so that special
effects and even imaginary characters can play a part in making movies, videos, and
commercials.

Page 46 of 47
ii. In sports, computers compile statistics, sell tickets, create training programs and diets
for athletes, and suggest game plan strategies based on the competitor’s past
performance.
(g) Government: Various departments of the Government use computer for their planning,
control and law enforcement activities, just to name a few. Traffic, Tourism, Information &
Broadcasting, Education, Aviation and many others.
(h) Defence: There are many uses computers in Defence such as:
i. They are used on Intercontinental Ballistic Missiles (ICBMs) that use Computers to
help the missile get to the target.
ii. Computers are used to track incoming missiles and help slew weapons systems onto
the incoming target to destroy them.
iii. Computers are used in helping the military find out where all their assets are
(Situational Awareness) and in Communications/Battle Management Systems.
iv. Computers are used in the logistic and ordering functions of getting equipment to and
around the battlefield.
v. Computers are used in tanks and planes and ships to target enemy forces, help run
the platform and more recently to help diagnose any problems with the platforms.
vi. Computers help design and test new systems.
(i) Sports: In today's technologically growing society, computers are being used in nearly every
activity.
i. Analyzing Movements: The best athletes pay close attention to detail. Computers can
slow recorded video and allow people to study their specific movements to try to
improve their tendencies and repair poor habits.
ii. Scoreboard: While some scoreboards are manually updated, most professional sports
venues have very modern scoreboards that are programmed to update statistics and
information immediately after the information is entered into the computer.

Page 47 of 47

You might also like