Sie sind auf Seite 1von 31

PART II

Introduction to computer science


Section A
Chapter One
Introduction
1.1

What is a computer?

It is not easy to describe a computer in a few words, but if one wanted to


define what a computer is, then the following would probably be adequate:
A computer is any machine or device which can accept data in prescribed
form process the data and supply the result of the processing in a specified
format as information or as signals to control automatically some further
machine or process.
A computer is a tool. A tool operates by raw material (data) and converting it
into a product (information) by means of a device which performs a process.
The process is determined by people.
Similar tools that can be used to process facts include the adding machine,
the slide rule. A dictionary, etc. all are used to process facts into information.
The main distinguishing features of a computer from other information
processing tools are speed, capacity and versatility. The computer is able to
achieve such feats because it is able to carry out a few extremely simple
operations accurately and very quickly.
1.2 Types of Computers
The three main categories are digital computers, analog computers and
hybrid computers.

Digital Computers
It works on data held as a large number of distinct items and operates in a
series of steps or instructions. Mostly used for commercial applications, also
by scientists and engineers engaged in the processing of large numbers of
mathematical calculations. Digital computers are the commonest computers
in the country and particularly in institutions computing centers. Some
examples of digital computers are IBM 360/370, PDP 11/34, and ECLIPSE
C60.
Analog Computers
These are types of computer which can accept data as a quantity varying
over a length of time, rather than series of distinct items each with a unique
value. Analog computers are mostly used in process control of industrial
operations and in simulation of processes.
Hybrid Computers
These combine some of the properties of both digital and analog computers.
Digital processing is usually faster and more sophisticated than the
processing which can be done by analog machines. We are mainly concerned
with digital computers in this manual.
1.3 Computer organization
Generally speaking, all computers consist of five functional parts:
Arithmetic and logical unit, memory or storage, input unit and output unit.
Memory

Input Unit

Control Unit

ALU

The functional parts of a Computer

Output Unit

All data to be processed must first be entered into the computer memory
through the input unit. The data in memory is manipulated by the arithmetic
and logical unit. The result of the manipulation will be stored in the memory.
The result can be displayed through any output device. The control unit is
the one co-coordinating all operations of the various units within the
computer.
We shall now look at the various units one by one.
Input and Output Units
Input unit is a device used in placing data in the computer memory.
Output unit is a device used to extract information (finished product) from
the computer.
Input and output units are usually electromechanical devices. This shows
that they have moving parts rather than pure electronic parts. There are many
types of input and output devices.
Examples of input device include the card reader, optical mark reader and
keyboards and commonly used output devices are the line printer, plotter and
card punch. Other devices such as tape drive, disk drive, magnetic drum,
terminals and teletypewriter can be used both as input and output devices.
Arithmetic and Logical Unit
This unit performs the arithmetic and logical operations on the data stored in
the memory. An example of an arithmetic operation in deducting tax from an
employees gross-pay, adding the transport and housing allowances to
produce the net-pay. Example of a logical operation is to determine the sex
of an employee.
Memory or storage
The memory is a unit used to store the data on which the arithmetic and
logical unit, and control unit are to work upon. The most common primitive
unit of storage in a computer is the bit (binary digit 0 or 1).

The memory of a computer may be regarded as an ordered sequence of


storage locations called memory cells. These cells have associated with them
distinct addresses, which indicate the relative position in the sequence.
The smallest, addressable unit of information on most computers (the
smallest unit which has a distinct address) is the byte which consists 8 bits.
A larger unit of information is called word and a word consists of 2 or
more bytes. For example, in the storage structure of the IBM system
360/370, a group of 4 bytes is referred to as a word. Similarly a half-word is
a group of 2 bytes while a double-word is a group of 8 bytes.
Control Unit
This is a unit which controls the activities or operations of each of the other
units. It supervises the sequence in which operations are performed. The
control unit receives instructions from the memory and decodes them for
execution. The unit of operation is called INSTRUCTION. Instructions are
sequence of operations. A program is a set instruction and these must be
resident in the memory where the control unit can have access to it in order
to direct the operations.
The control unit, and the arithmetic and logic unit are commonly referred to
as the central processing unit (CPU).
1.4

Programming Languages and Translators

A program is named according to the language used to write it. Hence, a


machine-language program, a BASIC program, a FORTRAN program, a
COBOL program and a PL/1 program could be written using the respective
programming languages. The purpose of the programming languages is to
established communication between the computer and their users.
The computers only understand instructions written in terms of electrical
signal symbolically represented as binary digits 0s and 1s. Writing a
complex program in such a language is terrible tedious and fraught with
opportunities for mistakes. In machine language, to add values stored in X
and Y would look something like:
0110 001110 010101
Where

0110 is the machine operation code for ADD while


001110 and 010101 are the addresses of X and Y.
Because of the difficulties with machine language programming, some
intermediate codes and high-level languages have been developed to enable
the programmer codes in a way that resemble his thought processes rather
than the elementary steps of the computer. This allows the programmer to
concentrate more on the logic of the program and less on the machine.
The most immediate step from machine language is the Symbolic Assembly
Language. Thus a programmer could write:
ADD X, Y instead of the above (i.e. 0110 001110 010101)
A computer can not execute a program written in this form (i.e. ADD X, Y).
The program that translates assembly language program to machine
language is called Assembler. A translator is a program that takes as input a
program written in one programming language (the source language e.g.
Assembly language and FORTRAN language) and produces as output a
program in another language (the object language)
Though, assembly language program is relatively simpler to understand than
machine language program, but is also has some drawbacks. The following
are the problems associated with it:
(1)
(2)
(3)

The programmer must still know the details of how the specific
computer operates
He must also mentally translate complex operations and data
structures into sequences of low-level operations
He must also be intimately concerned with how and where data is
represented within the machine

To avoid these drawbacks, high-level languages were developed. Basically, a


high-level language allows a programmer to express algorithms in a more
natural notation that avoids many of the details or how a specific computer
functions. So we could write:
A + B to add A and B.

The art writing programs in high-level languages makes programming task


simpler. The program that translates the high- level languages into a
language the machine understand is called compiler.
BASI, FORTRAN, COBOL, PL/1, PASCAL, LISP, C, ALGOL, SNOBOL
are some of the more common high-level languages.
In this manual, we are particular about BASIC.
Source program

Compiler

Object program

Translation Process
Another translator worth mentioning is the interpreter. Interpreters read the
source program directly, line by line, and generate the machine codes
necessary to carry out the instructions as they proceed through the program.
A compiler on the other hand, reads the source code and generates machine
code (called object code), usually saving it on a disk file. The object code is
loaded into the memory for execution. A language that uses interpreter is
BASIC.
CHAPTER TWO
Problem Solving With Computer
2.1 Algorithms
An algorithm is a step by step procedure that will solve a specific class of
problems. Examples are the square root algorithm, sorting algorithm,
traveling salesman algorithm, Newtons algorithm and a host of others. A
procedure is a finite sequence of well defined steps or operating, each of
which requires only finite amount of memory or working storage and takes a
finite amount of time to complete. An algorithm must have the following
properties:
1. Finiteness: an algorithm must be able to determine after a finite

number of steps the solution to a specific problem or non-existence of


a solution.
2. Definiteness: sequences of steps leading to a solution must be clear.
Unambiguous and capable of being rigorously followed. One problem
with this explanation is that the term Unambiguous is very

ambiguous. For example, an algorithm for crop-rotation in a farm may


be perfectly clear to someone who is familiar to farming techniques
and not to an historian or carpenter. So the capability within the
algorithm executor must be specified.
3. Input: it is not enough to prove that an algorithm is correct (finite and
definite), it is also necessary to ascertain the usage limits of the
algorithm. To do this we need a set of inputs that are allowable within
the spectrum of the algorithm.
4. Efficiency: many algorithm works well for some inputs cases and
poorly for others. It is desirable that all algorithms yield the desired
results without waste for any set of allowable inputs.
Examples:
1. Design algorithm for using elevator.
Step 1: Walk to the elevator door
Step 2: Press the button at the door chosen the appropriate one
(down or up) and wait for the elevator to arrive.
Step 3: Elevator door open.
Step 4: Enter the elevator.
Step 5: Press the button indicating the floor you are going to.
Step 6: Elevator door close.
Step 7: Elevator arrive at the floor.
Step 8: Elevator door open.
Step 9: Walk out of the elevator.
This algorithm assumes that you are the only one using the elevator at that
material time.
2. For each value of a, b, c, d, and x determine the value ax3 + bx2 + cx +
d
Step 1: Get a, b, c, d, x, (the values)
Step 2: Computer x and x
Step 3: Computer ax, bx, and cx
Step 4: Evaluate y = ax3 + bx2 + cx + d
Step 5: Obtain y.
Flowcharts
Flowchart is an important tool for planning the sequence of operations
before writing it. It is a symbolic or diagrammatic representation of

algorithms. It consists of a set of boxes, the nature of operations to be


performed along with connection lines and arrows that show the flow
of control between the various operations.
Common Flowcharts Symbols
Symbols
.

Functions
Direction of flow
Indicates range of a loop
Input to a program
Output from a program
Initialization, arithmetic calculation, and moving
data (operation)
Connector
Terminator
Decision box, comparison
Iteration box

Example 1
Suppose there are 25 values to be read. Each value is to be read, squared and
the resulting value printed.
Step 1: Set = 1 (I = counter)
Step 2: Read one value and store it X
Step 3: Square X and store Y
Step 4: Print the result stored in Y
Step 5: Is counter already 25? If yes, go to step 7

Step 6: Increase counter by 1. Go to step 2.


Step 7: Stop.
Steps to take in writing a complete program
There are number of basic tools which should be part of the working
knowledge of any one who design (writers) programs to solve problems
on a computer. In this section we shall look at some of the tools
1. Analysis
This should include the statement of the problem. Before we can
understand a problem, we must be able to give it a precise statement.
Then from description, we must decide whether we understand the nature
of the problem to solved, including perhaps some specific techniques to
be used.
The programmer must understand his/her data need, output expected, and
assumptions to be made. It is his/her responsibility to determine the
method of solution and the means to implement it.
2. Development of a model
A model is an abstraction of a real world problem after which a program
is built (written). Once a problem has been clearly stated and analysed,
the next step is to formulate a model. Modeling is an essential and
difficult task in developing a reliable program. Basic questions often
asked in choosing model include:
(i) which mathematical structure seems best for the problem?
(ii) are there other problems that have been solved which resemble this
one?
(iii) can we work with the model? Is it reasonably manipulable?
3. Design of an algorithm
The next step is to design an algorithm for solving the problem. Since we
have stated our problem in form of mathematical model, then we must
find a solution. The natural thing to do in finding a solution is to design
an algorithm. We must justify all steps taken and ensure that the
algorithm will terminate; and in doing so, the algorithm will have

examined all the necessary inputs and produce the expected results
(output).
4. Coding/programming
Now we have found a solution (algorithm) to the problem, the next step
is to develop (translate) the algorithm into a computer program.
Questions that readily come to mind include:
What are the values?
What are their types?
What subprograms are needed?
What programming language should be used?
5. Keypunching/ Data Entry
Next steps is to put the coding instruction in a specified input cards or
keyboards for input to the computer.
6. Program Testing
After the coding and keypunching, the next thing to do is to run the
program. This will help to ascertain the correctness of the program.
Testing the program will help get rid of syntactic, keypunching, and
logical errors. The programmer should ensure that he finally get the
program to run for a simple case (one that can be hand checked), and this
should be followed by a series of tests on the actual data until he has
done enough to be reasonably confident of the result.
Besides testing a program for correctness, other ways of test a program
include:
(i) Ascertaining the performance quality of the algorithm.
(ii)To determine the computational limitations of the algorithm.
These tests taken together try to provide experimental answers to the
questions: Does the algorithm work? How well does it work?
7. Execution

This is the actual program execution step, when the actual data are used,
and projects result collected. The step should be carried out only when
the program have been tested rigorously and certified correct.
8. Documentation
It is difficult to understand someone else raw code. The most obvious for
documentation is to enable individual to understand programs that they
did not write. It will also facilitate program changes, and make it easy to
use. Programs should make use of comments as much possible. A
program listing often includes:
The input specification
The output description
The deck set-up
Error messages and probable cause of machine constraints:
e.g. memory requirement, length of program execution and
devises used
SECTION B
Chapter One
Writing Programs in Basic
Preamble: Introduction a student to a programming language is like
introducing a student to a spoken language. Such introducing a student to
a spoken language. Such introduction usually starts with the allowable
alphabets. In BASIC programming language it will interest you to know
that more than the 26 English alphabets are used. This is one feature that
forms a key rudiment of learning a language. However, the three
attributes that form the rudiment of the BASIC programming language
are:
1. Well-defined characters/symbol what consist of the English alphabets
A Z, the numeric digits 0 9 and special symbols such as S, /, ;, :, *,
+, =, /, etc.
2. A set of commands or keywords such as INPUT, REM, GOTO,
DATA, END and so on. Keywords are specially defined words which
have special meaning to the computer in accordance with the defined
structure of the compiler chosen.

3. Phrases and sentences defined in accordance to laid down procedure.


Why BASIC programming language?
The word BASIC is an acronym for Beginner All- purpose Symbolic
Instructions code. It was designed to combine simplicity, of presentation, the
business orientation of COBOL (Common Business Oriented Language),
and powerful mathematical capabilities of FORTRAN (FORmula
TRANslation Language) and therefore it is more adequate for training than
any other programming language. And, it can solve wide varieties of
problems. One other advantage of the BASIC programming language is the
down to earth, lexical structure of BASIC. The most important thing in
programming is the logic supplied by the users.
Characters Applicable in BASIC
Basically, there are two types of characters namely constants and variables
Constants- these refer to characters which measures are understandably
informed however and wherever used. However, there are four types of
constants namely:
1 integer constant
2. Fixed and floating point constant
3. Logical constant
4. Literal constant.
1. Integral Constant integer constant is a whole number, signed or

unsigned. Some examples of integer constants are 100; 15; 10,


000,000; - 14; +218 etc.
2. fixed and floating point constant
A floating point refers to a rational (fractional number or generally real
number) or an integer, chosen to be represented, within the digits of
which point is placed arbitrary without changing the value of the number.
Example is 3.142. This could be written as:
3.142E+0
0.3142E+1

314.2E-2
3142.0E-3
0.003142E+3.
All these variance have the same value.
A fixed point number on the other hand refers to a representation convention
whereby the number 0 is written before decimal point and the nest number
range between 1 and 9. Examples are:
0.3142E+1
0.23E+2
0.9932E-4
to mean 3.142; 23.0; 0.00009932.
Logical Constant
Logical constant has two possible values namely TRUE and FALSE. And
the two operations that can be performed on then are called logical AND
logical OR. The various variances of logical constant by different
programming languages are;
0 and 1
TRUE And .FALSE
TRUE and FALSE
The BASIC language uses the last variance.
Literal Constant
Literal constant refers to a collection of characters placed between quotes.
Notice that a character is any symbol that can be used in computer.
Examples are :
AJIBOLA LECTURES COMPUTER SCIENCE
BIMBO BUBBLES
Y = A*x^2 + B* + C
FV = PV* (1 + R) ^ N

Variable A variable is an addressable location in the main memory of


computer. In BASIC there exist two types of variable viz:
1. Numeric variables
2. String variables.
Numeric Variables these are the addressable locations which accept
numbers. They are represented by the English alphabets A, B, C, Z;
combinations of alphabets followed by number, and/or special symbols.
Examples are A, A2, SUMEVEN, SALARY, etc.
String Variables- these are the addressable locations which accept literal
constants. The literal constants are usually double quoted. String variables
are represented by any combination of letter ended by $ symbol. Example
could be A$; DATA$, YINKA$; GRADE$; such that
A$ = STUDENT OF SYSTEMS ENGINEERING
DATA$ = 12
YINKAS = I AM 25 YEARS OLD, etc.
Important Notice: Due to the definition of variables, programs are written in
variables and not for a specific case (i.e. in constants)
CHAPTER TWO
Solving Problems with Computers
A computer does not do anything the user never asked it to do. Based on the
logic and the data supplied by user, the computer can perform wonders.
However, the logic must be made of well defined unambiguous statements,
made up of commands (or keywords), operators and operands. The logic
which solves a problem is called program.
Program: A program is a series of instructions (logical) assembled by the
user (called a programmer) used by the computer to carry out specific
procedure. There are different forms of structures called statements in a
computer program. These could be:
1.
2.
3.
4.

input/output statement
declaratives statements
assignment statement
conditional statement

5.
6.

looping/repetition/iterative statement
transfer/jump statement.

All the statements are made up of five key elements of BASIC programming
language, namely:
1.
2.
3.
4.
5.

Arithmetic operators
relational operators
functions
keywords
punctuation marks

And these are explained as follows:


Arithmetic operators these includes all the binary operators we are used to
right from our primary school days, they are parenthesis (bracket);
Exponential (index); multiplication; division; addition and subtraction. Just
like in BODMAS, these operations are performed in their order of priority
depending on the arrangement of expression to be supplied. The order of
priority is as follows:
1. Parenthesis ( )
as in 4* (3 + 2) = 4 *5 = 20
2. Exponential ^
as in 4 * 3^2 = 4 * 9 = 36
3. Multiplication/ Division */ as in (a) 4 + 3/2 = 4 + 1.5 = 5.5
(b) 4/2 3 * 5 = 2 15 = -13
There is no other arithmetic operation under heaven outside these four that a
computer can perform.
Note: Addition + and subtraction - are the same operator because rather
than write 3-4 you may have 3 + (-4); and multiplication * and division/
are same since is at par with 3* (1/4) or 3* 4^(-1).
Relational Operators These are operators used to relate (compare) two or
more numerical entities, resulting in logical operators true or false for the
truth h or falsehood of the relation. These operators are:
Equal to = as in x = 4
Less than < as in x < 2
Greater than > as in x >2

Less than or equal to < = as in x < = 6


Greater than or equal to >= as in x > = 3
Other examples are in usage;
1. If A <>B THEN A = B
2. let x <=Y THEN Y X > = 0.
Functions a function is a rule or law which defines the relationship
between two quantities.
Notable functions and their meanings are as follows:
Function

Meaning of the functions

ABS (X)
INT (X)
ATN (X)
EXP(X)
SQR (X)
SIN (X)
COS (X)
TAN (X)
SPC (X)
TAB (X)
SGN (X)

absolute value of X
greater integer not greater than X.
Arctangent of X
Exponential value of X
Square root of X
Sine of X
Cosine of X
Tangent of X
Leave X spaces
Start printing at (X+1)- th position
Sign of X sgn(X) = { -1 if x < 0
0 if x = 0
1 if x > 0

Remark: (1) no variable name can be represented by any of these functions


because the compiler will recognize such variable names as functions with
which the variable name had been represented.
(2) Functions have to be performed on a parameter.
Note: the second remark distinguished functions from commands or
statements.
Keywords These are the words which are uniquely defined in the context
of basic programming language. All the commands, functions, operators etc.
belong to this category. Some keywords are:

INPUT
AND
FOR.NEXT
OUTPUT OR
GOTO
ELSE
READ
DO
GOSUB
PRINT
LET
DIM
RETURN
REM
IF.THEN WHILE
END
STOP

SQR

Punctuation Marks these are the normal English punctuation marks,


namely;
Full-stop .
Comma ,
Semi-colon ;
Quotation mark
All these form the elements of BASIC programming language. It is the
combination of these five element that forms the required statements with
the logic that solves problems in a computer.
Some important BASIC statements are:

The REM statement


The input statement
The READ statement
The PRINT statement
The ASSIGNMENT statement etc.

Remark: we shall discuss some of these statements one after the other;
The REM statement- this refers to remark or comment which enables
intended users of a program to understand why, where and when the
program was written. Its purpose in a program is to document and it is
usually ignored by the compilers, because a REM statement does not
contribute to the logic of a program. The general format of REM statement
is
nn REM the remark expression
Example:

(1)
(2)

10 REM PROGRAM TO COMPUTE STUDENT DATA


15 REM PROGRAM TO CALCULATE ROOTS OF
POLYNOMIAL

The INPUT statement- These statements enable data to be fed into


compiler. Two keywords are responsible for this operation in the computer.
The two keywords are INPUT and READ. The difference between the two is
that when the keyword READ is used, you must complement it with DATA
just as the close of the subprogram, as in example 2 above; The general
format of input statement could be
nn INPUT variable, variable, . . .
nm READ variable, variable, . . .
mm DATA constant, constant, . . .

or

Example (1) a:
10 REM PROGRAM TO INPUT DATA
20 INPUT A, B, D$, WALE$
30 END
or what amount to the same thing.
Example 1 (b):
10 REM PROGRAM TO INPUT DATA
20 INPUT A
30 INPUT B
40 INPUT D$
50 INPUT WALE$
60 END
both program perform the same operation.
Example 2:
10 REM PROGRAM TO READ DATA
20 READ A4< B< COST$
30 DATA 50, -17, YOUR BILL is N20,000

40 END
Remark: The programs in example 1(a) (b) and (2) are only meant to read
(or input) those data but they will bring out the no answer on the screen
when they are run because you never requested the output from the
computer. To have output we use the PRINT statement.
The PRINT statement - With this statement any required information can
be output on the screen (VDU) of the computer in a predetermined format.
The general format is:
(nn) PRINT variable, variable . . .
Thus to show the Data that were read in example 2 above, we have the
following example:
15 REM PROGRAM TO PRINT READ DATA
20 READ A4, B, COST$
30 PRINT A4, B, COST$
40 DATA 50, -17, YOUR BILL IS $20,000
Remark: (1) When you run the program, the following output is shown on
the screen
? 50, -17, YOUR BILL IS $20, 000
(2) If you dont want everything on the same line you may write the same
program as follows:
10 REM PROGRAM TO PRINT READ DATA
20 READ 4A, B, COST$
30 PRINT A4
40 PRINT B
50 PRINT COST$
60 DATA 50, -17, YOUR BILL IS $20, 000
70 END
and the output on the screen will be
? 50
? -17
? YOUR BILL IS $20,000

(3) If you want to indicate which variable has what value then in any
chosen presentation mode chosen, you use the following kind of program.
For (2) below:
10 REM PROGRAM TO PRINT READ PROGRAM
20 READ A4, B, COST$
30 PRINT A4 =, A4
40 PRINT B = ; B
50 PRINT COST$ = COST$
60 DATA 50, -17, YOUR BILL IS $20,000
70 END
and your output looks like this
? A4 = 50
? B = -17
? COST$ = YOUR BILL IS $20, 000
(4) If you ended lines 30 and 40 in example 2 with coma, then you have
reverted to example 1, and your output will look exactly like they appear in
example 1, i.e. if you have written
10 REM PROGRAM TO PRINT READ DATA
20 READ A4, B, COST$
30 PRINT A4,
40 PRINT B,
50 PRINT COST$
60 DATA 50, -17, YOUR BILL IS $20,000
70 END
the output will be
? 50, -17, YOUR BILL IS $20,000
Thus, the comma mean the value of the next variable should be printed
immediately after variable behind which the comma is placed.

The ASSIGNMENT Statement This is a statement with allocate an


address (i.e variable) to an expression just like in mathematical problem
where we use variable say X to represent an expression as in:
LET X = a+b-c.
The general format of the assignment statement is:
nn LET variable = expression
Example: 23 LET X = A + (2B/C)
20 LET A(I) = 14 B
25 LET D$ = DAYO IS GENTLE
20 LET D = B^2 4*A*C
25 LET X1 = (-B + SQRT (D)/ (2*A).
It is applicable in program as follows:
Example: Write a program to find the future value of some money loaned
from Agbomagbe Bank Plc for n-year at the rate of 12% compounded semiannually.
Solution: The model for the problem is
FV = PV(1 + r/m)nm
Where m = 2, and a program may be as follows:
10 REM PROGRAM TO COMPUTE FV OF AN INVESTEMENT
20 INPUT PV, r, n30 LET R = 1 + r/m
40 LET N = nm
50 LET FV = PV* (R^N)
60 PRINT FV = ; FV
70 END.
Notice: In BASIC programming language the use of the key LET is
optional, thus the same program could be written;
10 REM PROGRAM TO COMPUTE FV OF AN INVESTEMENT

20 INPUT PV, r, n
30 R = 1 + r/m
40 N = nm
50 FV = PV* (R*N)
60 PRINT FV =; FV
70 END.
Remark: The problem solved with assignment statement only are straight
forward problems that refuse no critical decision at some points, it requires
no repetitive/recurrent/iterative operations. If such were involved then we
create a LOOP where there is a counter which enables the computer to
repeat the process for a number of times. For instance consider the
following:
Example1: Sum all the numbers between 1 and 100 inclusive.
100

Solution: Here, the statement of the problem is to find S, such that S = k .


k 1

There are two approaches:


(a) you may consider S as an arithmetic series and apply the formula
S=

n
T Tn
2
1

where Tn is the n-th term of the AP, substituting n, Ti, Tn in the formula we
have
S = 50* (1 + 100) = 50 * 101 = 5050.
And the program goes thus:
10 REM PROGRAM TO COMPUTE SUM OF AN AP
20 READ n, T1, T2
30 S = n* (T1 + T2)/2
40 PRINT n, = ,T1 = T2,SUM = ,S
50 DATA 100, 1, 100
60 END

(b) IF you are not mathematically sound then you may create loop using
various keywords and statements some of which are:
1. The ASSIGNMENT statement as counter
2. The IF . . . THEN . . . statement
3. The IF . . . GOTO . .. statement
4. The FOR . . . NEXT . . . statement
5. The IF . . . THEN . . . ELSE . . . statement
6. The DO . . . CONTINUE . . . statement
We shall discuss all this using our example. Notice that the additive identity
is 0. we therefore start summation from zero (i.e. 0) since S + 0 = S, thus
1. The ASSIGNMENT statement as counter
10 REM PROGRAM TO SUM BETWEEN 1 TO N
20 S = O
30 I = O
40 I = I + 1
50 S = S + I
60 IF I < 100 GOTO 40
70 PRINT S = ; S
80 END
Remark: in the last program, the whole logic is found in lines 40 to 60
where repetition is done 99 times. And this line 40 to 60 is called a loop.
Notice: When the LET is used, then (2) and/or (3) are used to take care of
the conditional logic (or simply put relational operations) in the program.
For instance line 60 in the program may be written:
60 IF I < 100 THEN 40
(^) takes care of (2) and (3) are now more than (4)
4. The FOR . . . NEXT statement applying this to the same problem we have
the following
10 REM PROGRAM TO SUM BETWEEN 1 TO N INCLUSIVE
20 READ S
30 FOR K = 1 TO 100

40 S = S + K
50 NEXT K
60 PRINT S = ; S
70 END
5. The IF . . . THEN . . . ELSE statement THE NATURE OF THE
OPERATION.
10 REM PROGRAM TO ROOTS OF A QUADRATIC
EQUATION
20 INPUT A, B, C.
30 P = A * C
40 D = B^2 (4*P)
50 IF D > = O THEN 60 ELSE 70
60 PRINT THE ROOTS ARE REAL ROOTS
70 PRINT THE ROOTS ARE COMPLEX ROOTS
80 END
Remark: the IF . . . THEN . . . ELSE statement enables us to define the
operation we want to perform on our variables if the condition stipulates in
the IF . . . THEN statement is false. The general format is:
(nn) IF condition THEN clause ELSE clause as in the statements
(a) 40 IF AGE > 40 THEN PRINT ADULT ELSE PRINT YOUTH
(b) 40 IF X = M THEN 50 ELSE GOTO 60
50 PRINT PAY AS YOU EARN
60 PRINT EXEMPTED etc.
Jumping Out of a loop There is provision to leave a loop if you desire,
you may then use the key word GOTO, or the conditional IF . . . THEN
statement. The following example will help students understanding.
10 REM PROGRAM TO SUM POSITIVE VALUES
20 SUM = 0
30 FOR I = 1 TO 10
40 READ X
45 IF X > 0 THEN
50 SUM = SUM + X
60 NEST I

70 PRINT X = ; sum
80 PRINT X = ; X
90 DATA 4, 15, -4, 10, 91
100 DATA 0, 9, 48, -2, 22
110 END
Another example could be the following
10 REM PROGRAM TO COMPUTE PRODUCT OF INTEGERS
20 PROD = 1
30 NOR J = 1 TO 4
40 READ P
50 IF R = INT (P) THEN 60 ELSE GOTO 80
60 PROD = PROD * R
70 NEXT J
80 X = INT (P)
90 PROD = PROD * X
100 PRINT PROD = ; PROD
110 DATA 14, 15.02, 19.10, 13
120 END
Another example is the following:
10 INPUT X
20 Y = SQR(X)
30 IF X < 0 THEN 50
40 GOTO 60
50 PRINT COMPLEX ROOT
60 PRINT THE SQUARE ROOT OF X IS; Y.
70 END
Nested loop- It is possible to have a loop within another depending on the
type of problem we are solving. Notice that two loops can not overlap each
other. an example of Nested Loop is as follows:
10 FOR I = 1 TO 6
20 PRINT * * * * * *
30 PRINT = = = = = =
40 GOTO 60
50 PRINT I AM QUALIFIED
60 PRINT = = = = = = = = = = = =

70 NEXT J
80 NEXT I
But the following example contains illegal loops
10 FOR I = 1 TO 3
20 PRINT MY RECORD IS CLEAN
30 FOR J = 2 TO 5
40 PRINT I AM PROUD TO BE A GRADUATE
50 NEXT I
60 PRINT PRAY WITHOUT CEASING
70 NEXT J
80 END
Remark: This is illegal in BASIC. If there should be more than one loops
then they must be entirely contained in one another.
The RESTORE command- Any time data are fed into the computer using
READ statement, the subroutine closes with a list of data which follows the
DATA- command. The RESTORE command returns the pointer to the start
of the DATA list. The general format is:
(nn) RESTORE this returns pointer to the start of the DATA list
also
(nn) RESTORE (line number) this return the pointer to the first
element of DATA statement on the line-number so chosen.
Example: consider the following program.
10 PRODUCT = 1
20 FOR I = 1 TO 10
30 READ A
40 PRODUCT = PRODUCT * A
50 NEXT I
55 M = J/10
60 PRINT PRODUCT =, N THROOTS PRODUCT
70 DATA 40, 2.43, 15.45, 32, 14.14
80 DATA 80, 2222, 0.37, 44, 17.
90 RESTORE
100 FOR J = 1 TO 10

110 READ A
120 PRINT DIFFERENCES OF N-TH ROOT FROM A; A N
THROOT
130 NEXT J
140 END
Notice that the last program computes the product of ten values, computes
the 10-th root of the product and obtains the difference between each value
and the computed 10-th root of the product.
CHAPTER THREE
Solving Practical Problem with Computer
Let us now apply what weve learnt so far to the kind of problems we are
familiar with
Question 1: Aseese Group of Companies (AGC) applied for a loan of
$15,000,000 at 20% compounded semi-annually from Boripe Bank Limited
payable in ten years. Write down the model to determine the total amount of
money Aseese Group of Companies will be required to pay back at the end
of the ten year, and write a programme for it.
Solution: Recall that this is asking for the future value of $15,000,000 at
20% compounded semi-annually in 10years. Thus,
FV = PV 1 r / 2 2n
Where r is the rate of interest, n is the number of years, PV is the present
value of the loan. The program is a straight forward one which requires no
loop. The following is a suggested program.
10 INPUT PV, r, n
20 Q = 1 + r/2
30 R = Q ^ (2* n)
40 FV = PV * R
50 PRINT PV = r = ; n = , n;
60 PRINT FUTURE VALUE IS; FV
70 END
Question 2: Write a program to solve the quadratic equation
2x2 7x + 5 = 0

Solution: Notice that the first point to consider is the determination of the
determinant
D = B2 - 4AC
Which determines the nature of the solution of the quadratic equation.
However, a program must take care of all possibilities.
Since there are three possible values of D namely
(i)
D > 0 with two distinct real values of D namely
(ii) D = 0 with two equal real values
(iii) D < 0 with two distinct complex values.
Then our program must take care of all the case, now the program.
10 READ A, B, C
20 D = B^2 = 4*(A*C)
30 IF D <> = 0 GOTO 70
40 X (1) = (1-B + SQR (D) / (2*A)
50 X (2) = (-B SQR (D) / (2*A)
60 GOTO 100
70 IF D = 0 GOTO 120
80 X(1) = - B/(2*A)
90 X(2) = B/(2*A)
100 PRINT X(1) = ; X(2) = ;X(2)
110 GOTO 160
120 REX(X) = - B/(2*A)
130 IM (X) = (SQR (ABS (D)))/(2*A).
140 PRINT REAL PART OF X IS; RE(X)
150 PRINT IMAGINARY PART OF X IS ; IM(X)
160 DATA 2, -7, 5
170 END
Notice that there is no remark in the program above, the reason is that it has
just been written and tested. Suppose we want to keep the program then we
put as many remarks as possible to make any future user understand the
program. This is what we referred to, in chapter two as documentation. If the
last program were to be documented, then, we have the following:
10 REM PROGRAM TO SOLVE QUADRATIC EQUATION
20 REM WRITTEN BY OJUOLAPE ENUOBO.

30 REM ON THE 26TH SEPTEMBER, 1999.


40 FOR THE HND1 BUS ADMIN. P/T.
50 SUBROUTINE TO DETERMINES DISCRIMINANTS
60 READ A, B, C
70 D = B^2-4*(A*C)
80 REM SUBROUTINE TO DETERMINE ROOTS WHEN D > 0
90 IF D < = 0 GOTO 180
100 X(1) = (-B + SQR(D))/(2*A)
110 X(2) = (-B SQR(D)0/(2*A)
120 GOTO 160
125 REM SUBROUTINE TO DETERMINE THE ROOT WHEN D
= 0
130 IF D < O GOTO
140 X(1) = -B/(2*A)
150 X(2) = -B/(2*A)
160 PRINT X(1) = ; X(1); X(2) = ; X(2)
170 GOTO 220
175 REM SUBROUTINE TO DETERMINE ROOTS WHEN D <
0
180 RE(X) = -B/(2*A)
190 IM(X) = (SQR (ABS(D)))/(2*A).
200 PRINT REAL PART OF X IS; REX)
210 PRINT IMAGINARY PART OF X IS ; IM(CX)
220 DATA 2. -7, 5
230 END
And this is when it becomes a library function.
Remark: The REM statement can be inserted any where in the program. It
does not disturb the logic of the program because the compiler skips it
anytime it identifies one.
Testing programs without Computer
This is called dry running. There is a way we can follow the logical
procedure of a program and check whether it is actually correct or not. If the
program flows then it only follows that if you input in a computer and run it
will run without hitch.
Consider the following program:

Example: Dry run the following program:


10 FOR 1 = 1 TO 3
20 PRINT * * * * * * *
30 PRINT = = = = = = =
40 NEXT I
Dry running gives the following result on the VDU (i.e. screen) of the
computer
*******
=======
*******
=======
*******
=======
Explanation: in dry running the program above, the compiler picks the
counter I from I, print * * * * * * * (i.e. line 20), it will then move to line
30 and print = = = = = = =. Then line 40 increases the counter by I and I
goes to 2. The same procedure is repeated, the counter increases to 3 and
then the same printing procedure equally take place. The result is what we
have printed after the program.
Dry Running a Nested Loop
This is a situation where a loop is completely included in another loop and
the running is done according to the logic or the nested loop. Considering
the fact that the outer loop controls the entries within itself, the inner loop
inclusive so when the counter pick the first set of entries the entire content of
the inner loop is executed before the outer loop moves to the next counter as
in the following example.
Example: Dry run the following program.
10 FOR I = 1 TO 5
20 READ X, Y
30 PRINT X + Y = ; X + Y
40 FOR J = 2 T0 4
50 PRINT * * * *

60 NEXT J
70 PRINT I HAVE FINISHED
80 NEXT I
90 DATA 5, 6
100 END
Solution: Following the logic of the program, the outcome looks like this on
the screen:
X + Y =11
*****
*****
*****
I HAVE FINISHED
X + Y = 11
*****
*****
*****
I HAVE FINISHED
X + Y = 11
*****
*****
*****
I HAVE FINISHED
X + Y = 11
*****
*****
*****
I HAVE FINISHED
X + Y = 11

Das könnte Ihnen auch gefallen