COMPUTER
SCIENCE
For Class
9" -1 0"
Part-2
WI
Punjab Textbook Board, Lahore.All rights are reserved with the Punjab Textbook Board. Lahore.
Prepared by: Punjab Textbook Board, Lahore.
Approved by: Federal Ministry of Education. Curriculum Wing, Islamabad.
vide its letter No. F.1-10/2005-Maths (Comp. Se.) Dated July 8, 2006.
CONTENTS a2
Chapter # Page ft
1 [PROBLEM SOLVING 1
2 |DATA TYPES, ASSIGNMENT AND 13
INPUT / OUTPUT STATEMENTS |
3 |CONTROL STRUCTURE 41
4 |ARRAYS 53
5 _|SUB-PROGRAM AND FILE HANDLING 61
6 —_|GRAPHICS IN BASIC ~
7 |MIcRosoFT woRD 89
* — |cLossary no |
+ _|InDEx 123, |
Syed Zulquenain Jaffery
Assistant Professor
COMSATS Institute of Information Technoloyy.
Sector H-8, Islamabad
Ms. Shahina Naz * Mr, Asif Ali Magsi
Head. Department of Computer Science. Lecturer (Computer Science)
Islamabad Model College for Girls, College for Boys, Islamabad.
F-10,2, Islamabad.
Editor Supervision
Mirza Mubasher Baig * Mr. Mazhar Hayat
Research Associate Subject Specialist
Department of Computer Science. Punjab Textbook Board, Lahore.
Lahore University of Management Sciences (LUMS), Lahore.Chapter 1
PROBLEM SOLVING
1.1 INTRODUCTION
We solve problems and make decisions everyday at home, at work, at play,
and even at the general store. Some problems and decisions are very challenging, and
require a lot of thought, emotion, and research. However, whatever the nature of the
Problem is, we always try to find multiple solutions so that we can have options to
choose the best one.
1.2 PROBLEM-SOLVING METHOD
Problem-solving is a skill which can be developed by following a well organized
approach. Programming is also a problem solving activity. If you are a good problem
solver, you have the potential to become a good programmer. Problem. solving
methods are covered in many subject areas. Business students learn to solve problems
with the related systems approach, while engineering and science students use the
engineering and scientific methods. Programmers use the software development method.
The following steps can be followed to solve any kind of problem:
(i) Problem identification Gi) Specify requirements
(Gil) Analyze the problem (iv) Design algorithm and draw flowchart
(v) Write the program (Coding) (vi) Test and Debug the Program:
(vii) Implement the program (viii) Maintain and update the program
(ix) Document the program
1.2.1 Problem Identification «
At this stage the problem being solved is observed carefully. Major
areas of concern afe identified and irrelevant information is filtered out.
Suppose we want to develop a simple calculator. Our major concern is how
basic arithmetic operations (addition, subtraction, multiplication and division)
are performed? How result should be displayed? How input should be accepted
etc.? We are not interested in how the Sine ot Tan are calculated? How is the
quadratic equation solved? And how are other mathematical operations
performed? These are irrelevant to us, so we shall not bother about these. In
this way, by filtering out irrelevant information we can concentrate on the
actual problem.
1.2.2. Specify Requirements
Most of the users can not explain their exact software requirements.
They are uncertain about what they want to do with the software. So they
appear with a vague set of requirements in mind which may lead to a wrong
solution. This stage demands to make clear the user's requirements so that a
proper solution could be suggested. This stage involves the formation of a
1 NOT FOR SALE - PESRPrequirements document which describes the features the system is expected t0
provide, the restrictions under which it must operate, and an abstract
description of the software which provide a basis for design and
implementation.
1.2.3. Analyze the Problem
‘At this stage the problem is decomposed mnto sub-problems. Rather on
concentrating the bigger problem as a whole, we try to solve each sub-problem
separately. This leads to a simple solution. This technique is known as top-
down design (also called divide and conquer rule). Here we may ask certain
questions to approach the right solution ew,
(How many solutions are there.to the given problem?
(i) Which one is the best solution?
(iil) Can the problem be solved on computer?
(iv) What are input and output?
(v) How can the bigger problem be divided into. sub-problems?
1.2.4. Design Algorithm and Draw Flowchart
Designing the algorithm requires to develop a finite list of steps to
solve a problem. It is then verified that whether the algorithm solves che
problem as intended or not. Writing algorithm is often the most difficule part
of the problem-solving process. Most computer algorithms perform at least
following three steps:
(i) Get data (Input)
(i) Perform computation (Processing)
(iii) Display results (Output)
Once the algorithm has been designed, it should be verified through
desk checking, Desk Checking is an important part of algorithm design that is
often overlooked. To desk check an algorithm, we must carefully perform
teach algorithm step just as a computer would do and verify that the algorithm
works as desired, The time and effort can be saved by locating and rectifying
algorithm errors at this stage.
‘A program is a set of instructions given to the computer to solve a particular
problem. Itis written in a programming language.
Desk Checking is the process of carefully observing the working of an algorithm, on
the paper, for some test data. Algorithm is provided a variable set of input for which
the output is examined.
Draw the Flowchart
‘After designing the algorithm, the next step is to draw a
flowchart. Flowchart, in fact, maps the algorithm to a pictorial
representation which helps in understanding the flow of control and
2 NOT FOR SALE - PESRPdata in the algorithm. We shall discuss in detail the way the flowchart
is drawn, later in this chapter.
1.2.5 Write the Program (Coding)
This step involves the conversion of an algorithm to a program, written
in any programming language. For this purpose, the programmer must know’
the syntax of the programming language chosen.
‘The grammatical rules of a programming language to write programs are referred to
as syntax of that programming language.
1.2.6 Test and Debug the Program
This stage requires evaluating the program to verify that it works as
desired, Don't rely on just one test case. Run the program several times using
different sets of data, making sure that it works cortectly for every situation
provided in the algorithm. If it is not producing desired results, then errors
(bugs) must be pointed out and debugged. Debugging is the:process of finding
and removing errors in the program. There can be three types of programming,
errors; syntax errors, run time errors (execution errors), and logical errors.
Debugging is the process of finding and removing errors in the program.
Syntax Errors
‘A syntax error occurs when the program violates one or more
grammatical rules of the programming language. These errors are
detected at compile time i.c., when the translator (compiler or
interpreter) attempts to translate the program. There can be many
reasons, fot example trying to execute a wrong program statement of
command such as typing PINT instead of PRINT statement; or trying
to assign a value to.a constant such as 5 = count ete.
Do You Know?
Division by zero is undefined.
Runtime Errors
A runtithe error occurs when the program directs the computer
to perform an illegal operation such as dividing a number by 2er0.
Runtime errors are detected and displayed by the computer during the
execution of a program. When a runtime error occurs, the computer
will stop executing the program and may display a diagnostic message
that helps in locating the error.
Logical Errors
Logic errors occur when a program follows a wrong logic. The
translator (compiler or interpreter) does not report any error message
for a logical error. These are the most difficult errors to locate. Logical
errors can he identified by just looking at the wrong output of the
program. Logic errors can only be detected by thoroughly testing the
% NOT FOR SALE - PESRP13
program, observing all variables closely and testing each path of logic
flow in the program.
1.2.7 Implement the Program
Once the program has been as tested thoroughly, it must be installed
‘or put into operation at the site where it will be used. This is known as
implementation of the program.
1.2.8 Maintain and Update the Program
Program maintenance is an ongoing process of upgrading the program
to accommodate new hardware of software requirements, and introducing
minor improvements, Essentially, it is the expansion, updating and
improvement of a program after its installation, Regular maintenance is
essential to the continued usefulness of a program. A proper maintenance
depends on the existence of complete documentation.
1.2.9 Document the Program
Documentation is a detailed description of @ program's algorithm,
design, coding method, testing, and proper usage. Documentation is valuable
for the users who rely upon the program on a day-to-day basis, and for the
programmer who may be called on to modify or update it.
There are no universally accepted standards concerning what should
be included in a program’s documentation. Although its contents will vary
somewhat depending on the complexity of the program, in general,
comprehensive documentation consists of the following:
* A description of what the program is supposed to do (software
requirement document).
* A description of the problem solution (the algorithm).
© A description of the program design, including any aids used
(flowcharts, algorithms etc.).
* A description of the prograi
used and results obtained.
's testing process, including the test data
© A description of all corrections, modifications, and updates made to
the program since it was put into operation.
© Auser manual (user guide).
ALGORITHM
An algorithm is a finite set of steps which, if followed, accomplish a particular
task. An algorithm must be clear, finite and effective. The simplest form of algorithm
is step-form algorithm (like a to-do list) It consists of a sequence of numbered steps
1.3.1. Strategy for Developing Algorithm
Algorithm development involves the following steps to carry out. We
can proceed to correct solution of a particular problem by adopting the
following strategy.
4 NOT FOR SALE - PESRPStep 1: Investigation
(i) Identify the processes.
(i) Identify the major decisions.
(iil) Identify the repetitions.
(iv) _ Identify the variables.
Step 2: Preliminary algorithm.
(Devise a high-level (general) algorithm.
(ii) Step through the algorithm. Does this "walk-through" reveal
any major problems? If it does then correct the problems.
Step 3: Refining the algorithm
(i) Incorporate any refinements indicated in step 2.
(i) Group together processes where appropriate.
(ii) Group together variables where appropriate.
(iv) Test the algorithm again by stepping through it.
Let us consider the following example to understand the way of
approaching a solution to a problem.
Problem 1: You have to bake a cake in your house.
Step-form Algorithm
The following diagram shows the steps to follow to bake the cake.
Step 1
Step 2
Step 4
Step 5
v
Heat oven to 325°F
Milk
Flour
Gather the ingredients Eogs
S9¥=she
—_ &
Mix ingredients thoroughly
ina bowl
Pour the mixture into a
baking pan
Bake in the oven
50 minutes
3 NOT FOR SALE - PESRPStep 6 — Repeat
Bake 5 minutes more
Until cake tep springs back when touched in the canter
Step 7 Coo! on arack before cutting
‘Step-form Algorithm: Baking a cake
Problem 2
‘Making tea: You have to make tea in your house.
Step-form Algorithm
‘An initial attempt at an algorithm might be:
1. Put tea leaves in pot
2. Boil water
3. Add water to pot
4. Wait 5 minutes
5. Pour tea into cup
First Refinement
© These steps are probably not detailed enough to make tea. We therefore refine each
step into a sequence of further simpler steps:
Step 1: Put tea leaves in pot
Te might he refined to
1.1 Open box of tea
1.2 Extract one spoorful of tea leaves
1.3. Put spoonful into por
1.4. Close box of tea
Step 2: Boil water
Iemighe be refined to
2.1 Fill kettle with water
2.2 Switch on kettle
2.3 Wait umtil water is boiled
24 Switch off kettle
Step 5: Pour tea into cup
Te might be refined to
5... Pour tea from pot into cup
until eup is full
©) Second Refinement
Some of the refined steps may be further refined. For example step 2 can be refined as:
Step 2.1 Fill kettle with water
Te might be refined to
6 NOT FOR SALE -PESRP2.1.1 Put kettle under tap
2.1.2 Turn on tap
2.13 Wait until kettle is full
2.14 Tum off tap
Other steps may also require further refinement. After a number of refinements the
robot is able to execute every step.
Original Algorithm Eirst Refinement Second Refinement
1, Put tea leaves in 1.1 Open box of tea 1.1.1 Take tea box from shelf
pot 1.1.2 Remove lid from box
1,2 Extract one spoonful
1.3 Put spoonful into pot
1.4 Close box of tea 1.4.1 Put lid on box
1.4.2 Replace tea box on shelf
1 Put kettle under tap
2.1.2 Turn on tap
2.1.3 Wait until ketcle is full
2.1.4 Turn off tap
2. Boil Water 2.1 Fill kettle with water
2.2 Switch on kettle
2.3 Wait until water boiled — 2.3.1 Wait until kettle whistles
3, Add water to pot. 24 Switch off kettle
Warerio Pol’ 3.1 Pour water from kettle
4, Wait 5 Minutes sonal por is full
5. Pour tea into cup
5.1 Pour tea from pot into
cup until cup is fall
Example 1: Write an algorithm to find | Example 2: Write an algorithm to find
the sum of first 50 natural numbers. the factorial ofa given number
Algorithm Algorithm.
BEGIN BEGIN
SUM =0 fact = 1
N= n=l
DO WHILE ev <=50) PRINT “Enter a number
SUM = SUM +N INO a
y FORn = Ltonum
Ne fact = fact * n
END DO NEXT a
END PRINT fact
END
3. NOT FOR SALE - PESRP.14 FLOWCHART
Flowchart is the pictorial representation of an algorithm. It is a way of visually
presenting the flow of data, the operations performed within the system and the
sequence in which they are performed. The flowchart is similar to the layout plan of a
building. As we know a designer draws a layout plan before starting construction on a
building. Similarly, a programmer prefers to draw a flowchart prior to writing a
edmputer program. As in the case of drawing of a layout plan, the flowchart.is
drawn according to defined rules.
1.4.1 Symbols of Flowchart
Flowcharts are usually drawn using some standard symbols; however,
other special symbols can also be developed when required. The standard
symbols which are frequently used in flowcharting are shown below:
8) Start/End of a flowchart
Processing
iT Input/ourput
|t Flow lines
FT Pre-defined Process
LD) | tinerionsiubrrvins)
eee Remarks
1.4.2. Guidelines for Drawing a Flowchart
a. In drawing a flowchart, all necessary requirements should be listed in a
logical order.
b. The flowchart should be clear, neat and easy to follow. There should
not be any ambiguity in understanding the flowchart.
cc. The usual direction of the flowchart is from top to bottom or left to
right.
d. Only one flow line should come out fiom a process symbol.
8 NOT FOR SALE - PESRP14.3
144
d
= ee
or f
Only one flow line must enter a decision symbol, but two flow lines,
‘one for each possible answer, must leave it.
eee
‘Only one flow line is used in conjunction with terminal symbol. Ensure
that the flowchart has a logical start and end.
Write comments within Remarks symbol. We can use the remarks
(annotation) symbol to describe steps more clearly.
~"| This is confidential data
If the flowchart becomes complex, itis better to use connector symbols
to reduce the number of flow lines. The intersection of flow lines
should be avoided to make it more effective and clear.
Ie is useful to test the validity of the flowchart by passing through it
with a simple test data.
Advantages Of Flowcharts
The benefits of flowcharts are:
() With the help of a flowchart, the logic of an algorithm can be
described more effectively.
(i) As flowcharts are part of the design document, hence
maintenance of operational programs becomes easy.
(iti) ‘The flowcharts act as a guide for the program development.
Thetefore, they help the programmer to put efforts more
efficiently on the underlying problem.
(iv) The flowchart helps in debugging process.
Limitations Of Flowcharts
(i) It is difficult to draw flowcharts for complex problems.
(ii) Tfalferations are required, the flowchart is to be redrawn.
5 Teo Sake peeExample 3: Draw a flowchart to find the | Example 4: Draw a flowchart to
sum of first 50 natural numbers. find the factorial of a number
am)
SUM=0
1. Fill in the blanks:
(i) The set of instructions given to the computer to solve a problem is
called
(i) The set of rules for writing programs in a programming language is
known as, of the language.
(iii) Flowchart is a representation of algorithm.
(iv) An algorithm solves a problem in. number of steps.
(v) During a problem is decomposed into multiple sub-
problems.
(vi) Debugging is the process of finding and removing ina
program,
(vii) Program refers to the installation of the program in the
user environment.
(viii) Occurrence of a error crashes the program.
2. Choose the correct answer:
() — BASICisa:
(a) High Level Language (b) Low Level Language
(©) Assembly Language (d) Machine Language
10 NOT FOR SALE - PESRPGi)
(ii)
(iv)
(w)
(vi)
(vii)
(viii)
(x)
&)
How many possible solutions are there for a problem?
() One (b) Two
(©) Three (@) Multiple
Program upgradation refers to:
(a) Program enhancement (b)_ Program identification
(©) Program development (d)’ Program implementation
‘Which of the following tasks are performed by most of the algorithms?
(a) Input (b) Output
(©) Processing (@) All of these
‘Typographical errors in BASIC statements are:
(2) Runtime errors (©) Logical errors
(©). Syntax errors (@)_ Execution errors
‘The diamond symbol represents the:
(a) Input/Output (b). Decision miaking
(c)_ Processing (d) | Remfarks
Division by zero is:
(a) Syntax error (b) Logical error
(©) Runtime error (@) Not an error
Which of the following documents describe various features of the
software and the way it is used?
(a) Software requirement (b) Problem description
specification
(©) User manual (@)_ Algorithm
Algorithm is a:
(a) Requirement document (b) Design document
(©). Test document (d)_ user guide
The technique ‘Divide and Conquer’ is used to solve:
(a) Simple problems (b) Complex problems
(c)_ Large problems (d)_ Complex and large problems
Write T for True and F for False statements.
@
(i)
(iii)
(iv)
@)
(vi)
(wii)
(viii)
(oo)
Syntax errors occur due to wrong program logic.
“Top-down design is followed to solve complex problems.
Desk{checking is the process of verifying the working of an algorithri.
Debugging is an important part of analysis
Every stage of program development is documented.
‘A rectangle symbol is used for decision making in a flowchart.
Requirement document is not helpful at development stage.
The usual direction of flowchart is from right to left
Annotation symbol is used for writing comments.
ul NOT FOR SALE - PESRP-
What do you mean by problem solving? Briefly describe the problem solving
process.
5. What is debugging? How many types of errors can occur in a program?
Describe briefly.
6. Define algorithm. Write a step-form algorithm for making a telephone call to
your friend.
7. What are the advantages of flowchart? Discuss limitation of flowchart.
8 Draw flowchart to find the largest of three numbers.
9. Write an algorithm to calculate the area of a circle when the radius is given.
(area = 3.14 * radius * radius)
10. Answer the following short questions:
(i) List steps that should be followed to solve a problem.
(i) Whats analysis? Describe its importance in solving a problem.
(iii) What method should be adopted to solve complex problems? Discuss
briefly.
(iv) What do you mean by syntax of a programming language? Is it
necessary to know the syntax for solving a problem on computer?
(%) Differentiate runtime errors and logical errors.
(vi) Why documentation is considered vital in. problem solving process?
Give reasons.
(vii) Is it necessary for an algorithm to solve a problem in finite number of
steps? Ifyes, why?
(vit) Write purpose of the following flowchart symbols:
Dc n/m
) »o O (wi)
(x) Compare flowchart and algorithm.
(0) Write an algorithm to calculate the distance covered by a car moving
at an average speed of v ms" in time t. The program should input
average speed @ and time t,
(Hi vt, where s is the distance traveled]
() Program (ii) Syntax (ii) Pictorial (iv) Finite
(v) Analysis (vi) Errors (vii) Implementation (viii) Runtime
RB @ oa (i) od Gi) a iw) dw) oe
wi) ob (vil) € (vii) @&® b @ d
BSE fi) F Gi) TW) T & F
wi) (vi) F (vit) Fo @) F @ T
2 NOT FOR SALE - PESRPChapter 2
DATA TYPES, ASSIGNMENT AND
INPUT/OUTPUT STATEMENTS
2.1 INTRODUCTION
The BASIC language was developed by John Kemeny and Thomas Kurtz if
1963 at Dartmouth College, USA. It was invented as an instructional tool to teach
fundamental programming concepts to students. It was developed to address the
complexity issues of older languages.
GW-BASIC is an interpreterfor BASIC (Beginner's All-Purpose Symbolic
Instruction Code) language. There are many other translators (compilers and
interpreters) for BASIC from different vendors such as QBASIC (Quick BASIC)
which provides a menu-driven envitonment to write and execute BASIC programs.
Here we shall refer to only GW-BASIC because it provides a simple and easy t0 use
environment.
2.2 MODES OF OPERATION
GW-BASIC can operate in two modes ie., direct mode and indirect mode.
‘When GW-BASIC is loaded, it shows ok message. At this stage, itis in direct mode.
In direct mode, GW-BASIC commands are executed as they are typed. Results
of arithmetic and logical operations can be displayed immediately, but the commands
themselves are lost after execution. This mode is useful for debugging and for quick
‘computations that do not require a complete program.
Fig. 2.1: Example of Direct Mode
‘The indirect mode is used to type programs. Program statements are always
preceded by line numbers, and are stored in memory. The program loaded in memory
is executed by entering the RUN command (fig. 2.2).
Fig. 2.2: Example of Indirecr Mode
13 NOT FOR SALE - PESRP© GW-BASIC commands are executable instructions which are operated in the
direct mode. They do not require a preceding line number.
© GW-BASIC statements. are written as a program and each statement is
preceded by a line number.
2.3 WRITING PROGRAMS IN GW-BASIC
GW-BASIC provides an IDE (Integrated Development Environment) where
we can write, edit, save, load and execute BASIC programs (fig,
/-BASIC IDE
2.3.1 Create and Save the Program
The program is a file that contains specific instructions, ot statements,
{for the computer. In a GW-BASIC program, lines have the following format:
Line# statement(s)
where, Line# is an unsigned integer in the range from 0 to 65529 and
statement(s) is any valid GW-BASIC statement. A GW-BASIC program line
can not have more than 255 characters. However, there may be more than
one statement on a line. If so, each must be separated by a colon (). The
program’s statements are executed depending on line numbers in ascending
order. For example, if line 45 is typed after line 60, the computer would still
run line 45 before line 60.
Reuse of an existing line number causes all of the information contained in the
original lin to be lost. You may erase some program lines by accident
In otder to use the program in future, we must save it. To save a file in
GW-BASIC, the following procedure is used:
(Press the F4 key or type SAVE command.
Gi) Type a valid name (in quotes) for the program, and press the ENTER
key. The file is saved under the specified name.
14 NOT FOR SALE - PESRP24
2.3.2 Load the Program
Loading the program refers to bring it into memory from secondary
storage device such as hard disk, so that it can be used. A saved program can
be loaded by using the following procedure:
i) Press the F3 key or type LOAD command.
(ii) Type the name of an existing file (in quotes).
(iii) Press ENTER.
The file is loaded into memory, and is ready to list, edit, or run,
If the file does not exist or an invalid path is tybed, an error message is displayed.
The default extension of GW-BASIC program is .bas
To save the file in a directory, you should specify the complete path with the file
name. Otherwise the file will be saved in the current working directory of GW=
BASIC.
3.3. Execute the Program
Execution of the program refers to carrying out instructions of the
program. The program must be loaded into memory (RAM) before execution.
Therefore to execute a program, first load it as described above. Then press F2
key or type RUN command, the output of the program will follow it.
Oh
Pavey,
RUN
UM
Fig. 2.4: Creating and saving the program | Fig. 2.5: Loading and running the program
Structure of the BASIC Program
Every BASIC program should follow the following rules.
() Every program statement must begin with a line number
(i) It is a good practice to end every BASIC program with an END
statement. However, itis not mandatory.
(iti) Repetition of line numbers within a program is not allowed
(iv) Two ot more statements can be written on a line but they must be
separated by a colon (:)
(¥) In BASIC, variables can be used without declaration.
(vi) In a BASIC program, the physical appearance of the program
statements does not matter. For example, in a program line number 90
can appear before line number 60; however the program statements
will always execute according to the ascending order of specified line
numbers.
15 NOT FOR SALE - PESRP2.5 Character Set of BASIC
Character set of a language defines all characters which are valid to use in
programs written in that language. The character set of GW-BASIC comprises of
alphabets, numeric and some special characters.
* The alphabets include uppercase and lowercase letters
© Numeric characters include digits from 0 to 9
* GW-BASIC characters set include the following special characters
Character
= Equal sign or assignment symbol.
+ Plus sign or string concatenation.
« Minus sign.
. Asterisk or multiplication symbol.
/ Slash or division symbol.
Caret, exponentiation symbol, or CTRL key.
( Left parenthesis.
) Right parenthesis.
% Percent or integer declaration.
# Number sign or double-precision declaration.
>. Dollar sign or string declaration
! Exclamation point or single-precision declaration.
[ Left bracket.
1 Right bracket.
# Comma.
a Double quotation marks or string delimiter
Period, dot, or decimal point.
Single quotation mark, apostrophe, or remark indicator.
3 Semicolon or carriage return suppressor.
: Colon or line statement delimiter.
& ‘Ampersand or descriptor for hexadecimal and octal number
conversion.
? Question mark.
16 NOT FOR SALE - PESRP< Less than symbol.
> Greater than symbol.
\ | Backslash or integer division symbol.
@ "At" sign,
— Underscore.
BACKSPACE | Deletes last character typed.
ESC Erases the current line from the screen.
TAB Moves print position to next tab stop. Tab stops are every eight
columns.
ENTER ‘Terminates input to a line and moves cursor to beginning of the
next line, or executes statement in direct mode,
2.6 RESERVED WORDS
Reserved words or keywords are the words, which have predefined meaning
in BASIC. These have predefined uses and cannot be used or redefined for any other
purpose in a BASIC program. Keywords carinot be used as variable names. Some of
the keywords of BASIC are IF, ELSE, THEN, WHILE ete.
2.7. VARIABLES
Variables are named memory locations (memory cells) which are used to store
program's input data and its computational results during program execution.
As the name suggests, the value of a variable may change during the program
execution. If a variable is assigned no value, the GW-BASIC assumes the value of
variable to be zero in case of numeric variables and nuill to string variables.
2.7.1 Rules for Naming Variables in BASIC ,
Each variable that is used in a BASIC program must have a name. The
name of a variable is used for further references made to it. The value of the
variable is accessed by its name. In GW-BASIC, there are some rules for
‘naming variables. These are:
@) In GW-BASIC, a variable name can not be more than 40 characters
long.
(i) ‘The variable name may contain alphabets (both uppercase and
lowercase), numbers, and the decimal point.
(iii) The first character in the variable name must be an alphabet.
(iv) Reserved words can't be used as variable names.
(¥) Blank spaces are not allowed in variable names.
(vi) However, the last character of a variable name may be a special type
declaration character indicating the type of a variable.
If type of a variable is not specified, i i assumed as a Real type variable.
7 NOT FOR SALE - PESRP2.1.2. Type Declaration Characters
In GW-BASIC, type declaration characters represent the type of
variable. Following type declaration characters are recognized in GW-BASIC.
Character __| Type of Variable Example [Memory Required
$ String variable ‘Name$ | String length
% Integer variable Marks% | 2 Bytes
! Single-precision variable | Avg! __| 4 Bytes
# Double-precision variable | Area# | 8 Bytes
2.7.3. Types of Variables
“There are two basic types of variables:
. Numeric Variables
© String Variables that can store strings of characters
Numeric Variables
‘Numeric variables can store numeric values (Numeric values
include both floating point numbers and whole numbers). If we don’t
specify the type of a numeric variable, GW-BASIC considers it as
single-precision. Single-precision variables can accurately handle
numbers up to six significant digits, however it can not handle seventh
significant digit accurately. If more accuracy is desired, we should
rather use double-precision.
String Variables
‘A string can be defined as a sequence of characters enclosed in
double quotations. A string variable can therefore store sequence of
characters. The nature of character string is entirely different from the
nature of numeric values. BASIC and other languages use different
formats for storing numeric and'string data. InBASIC, a dollar sign ($)
4s followed by the name of the string variable. We can not perform the
same set of operations on strings that we can perform on numeric
values. For example, strings can not be added, subtracted, multiplied or
divided. There ate some other operations that can be performed on
strings such as concatenation and comparison.
Be very careful when making conversions between integer, single-precision, and
double-precision variables. Otherwise you may lose accuracy accidentally.
2.8 CONSTANTS
‘A constant is quantity whose value can not be changed. Unlike a variable,
the value stored in a constant can't be changed during program execution. In BASIC,
there are two types of constants. These are numeric constants and string constants.
2.8.1 Numeric Constants
Numeric constants consist of integers, single-precision, or double~
precision numbers. Integer constants represent values that are counted and do
18 NOT FOR SALE - PESRP29
not have a fractional part e.g., +56, -678, 8, etc. Single-precision or double-
precision numeric constants represent values that are measured and may
contain fractional part ¢.g., - 4.786, 5.0, 0.45 etc. Single-precision numeric
constants are stored with 7 digits (although only 6 may be accurate). Double-
Precision numeric constants are stored with 17 digits of precision, and printed
with as many as 16 digits.
A single-precision constant is any numeric constant with either
. ‘Seven ot fewer digits
© Exponential form using E
¢ A trailing exclamation point (!)
A double-precision constant is any numeric constant with either
. Eight or more digits
. Exponential form using D
. A trailing number sign (#)
The following are examples of single- and double-precision numeric constants:
Single-Precision Constants ~Double-Precision Constants
23.08 342237861
-3.15E-04 -5.35857D-06
2145.0 3220.0#
37.4 1645721.1334
2.8.2 String Constants
A string constant is a sequence of alphanumeric characters enclosed in
double quotation marks. The maximum length of a string constant is 255
characters. For example, “Lahore”, “4900”, “I love Pakistan” etc.
BASIC COMMANDS
Here are some commonly used commands of BASIC language.
2.9.1 AUTO Command
This command automatically generates line numbers in an incteasing
order, each time the ENTER key is pressed.
Syntax:
© AUTO [line number] [increment]
© AUTO [increment]
Interpretation: +
AUTO is useful for typing a program because it relieves us
typing line numbers again and again. In the above syntax [line number]
specifies the starting line number of the program, whereas {increment]
19 NOT FOR SALE - PESRPspecify the subsequent increment to the previous line number. The
default for both values is 10.
The period (.) can be used asa replacement for line number to
indicate the current line. If fincrement] after the line number is omitted,
the last increment specified in an AUTO command is assumed.
If AUTO generates a line niember that is already being used, an
asterisk appears after the number to war that any input will replace
the existing line. However, pressing ENTER immediately after the
asterisk saves the line and generates the next line number.
‘AUTO is terminated by entering CTRL-BREAK or CTRL-C.
GW-BASIC will chen return to command level.
Examples:
© AUTO 100, 20
Generates line numbers 100, 120, 140, and soon
+ AUTO
Generates line numbers 10, 20, 30, 40, and so on
« AUTO, 50
Generates line numbers starting from the line number specified
in the last AUTO command with the increment of 50
* AUTO
Generates line numbers starting from the current line number
(jce., the last line number generated from the previous AUTO
command) with the increment specified in the previously
entered AUTO command.
2.9.2. CLEAR Command
This command sets the values of all numeric variables
to zero, the values of all string variables to null opened and
closes all files.
‘Syntax:
CLEAR
Example: The adjoining figure shows the effect of
CLEAR command.
Fig. 2.6: Example of
CLEAR Command
2.9.3. CLS Command
‘This command is used to clear the screen.
Syntax:
CLS [n)
20 NOT FOR SALE - PESRPInterpretation:
Here n is optional, but it can take any of the following values:
Value of n Effect
0 Clears the screen of all text and graphics
I Clears only the graphics
2 Clears only the text
Example:
. CLS (Type CLS at command level)
es 9) OLS
2.9.4 DELETE Command
‘This command is used to delete program lines or line ranges of loaded
program.
2.9.5
Syntax:
* DELETE [line nember1]|- line number2}
© DELETE line number] —
Examples:
© DELETE70
Deletes line 70.
. DELETE 50-150
Deletes lines 50 through 150, inclusively
. DELETE -80
Deletes all lines from start up to including line 80
. DELETE 120-
Deletes all lines from line 120 to the end of the program
EDIT Command
This command is used to modify a program line.
Syntax:
© EDIT line maber
. EDIT.
Interpretation:
line number is the number of che program line which we want to
edit. The period (.) refers to the current line.
Examples:
° EDIT 140
Displays program line number 140 for editing
° EDIT.
Displays the current program line for editing
a NOT FOR SALE - PESRP2.9.6 FILES Command
This command is used to list the names of all files residing on the
specified drive.
2.9.7
Syntax:
FILES [pathname]
Interpretation:
[pathname] is the optional parameter which if omitted; the
command lists all files in the current directory of the selected drive.
‘Wildcards such as * (asterisk) and ? can also be used in pathname.
Question mark (2) is used to match any characters in the filename or
extension, and asterisk (*) is used for any filename or extension.
Examples:
° ‘FILES
Lists all files in the current directory of the selected drive
«FILES “*.doc”
Lists all files whose extension is doc
. FILES “D:*.*”
Lists all files on the D: drive with any extension
® FILES “Mar?.xls”
Lists all files
‘Whose extension is xls
‘Whose name consists of four characters
First three characters of their names are Mar and the fourth
character could be any
Fig. 2.7: Example of FILES Command
KILL Command
This command is used to remove/delete a file from the disk.
Syntax:
KILL filename
Interpretation:
KILL command is used to delete all types of files.
2 NOT FOR BALE - PEBRP2.9.8
Examples:
. KILL “Inventory.bas”
Deletes the file Inventory.bas in the current directory
© KILL “G:\Goods\Inventory.*”
Deletes all files named Inventory with any extension
Be careful while using KILL command. Always specify the filename's
extension when using the KILL command. You may lose your data
accidentally while using this command.
LIST Command
This command is used to display a loaded program partially or
completely on the screen.
2.9.9
Syntax:
* LIST [line number}{—line number] [ filename]
© LIST [line number -|[ filename}
Interpretation:
In the above syntax, all parameters are optional which if
omitted; the command lists the last entered program. [line number] is a
valid line number within the range of 0 to 65529. If filename is not
specified with the LIST command, the specified lines of the last
typed/loaded program are listed.
Examples:
«ist
Lists all lines in the program
* — usT-20
Lists lines of the programs up to the line number 20
. LIST 10-20
Lists lines from 10 through 20
. LIST 20-
Lists lines 20 through the end of the program.
LOAD Command
This command loads a file from disk to memory.
tax:
LOAD filename|,r]
Interpretation:
filename is the name of the file to be loaded. If the {r] option is
used with LOAD command, the program runs after it is loaded.
Examples:
. LOAD “D:\fact.bas”
Loads the file named fact.bas from D: drive
. LOAD “Di\fact.bas”, r
Loads and executes the file fact.bas from D: drive
2B NOT FOR SALE -PEBRP2.9.10 MKDIR Command
This command is used to create a subdirectory.
Syntax:
MEDIR pathname
Interpretation
pathname identify the location where the subdirectory is
created. It is a string expression that should not exceed 63 characters.
Example
MKDIR "D:\Goods\Inventory"
Creates the subdirectory Inventory within the directory of
Goods.
2.9.11 NAME Command
This command is used to rename a file.
Syntax:
NAME oldflename AS new-filename
Interpretation:
The file will be renamed; the old-filename is replaced by the
new-filename
Example
NAME “Remarks.doc” AS “RMKS.doc”
Gives the name RMKS.doe to the file Remarks.doc
2.9.12 RENUM Command
‘This command is used to renumber the program lines.
Syntax:
RENUM [new number], [old number] [,increment]}
Interpretation
New mumber is the starting line number in the new sequence.
The defaule is 10. old number is the line in the current program where
renumbering is to begin. The default is the first line of the program,
increment is the increment to be used in the new sequence. The default
is 10.
Examples
* RENUM
Assign new numbers to the whole program (if different)
starting from line# 10 with the default inerement of 10.
© RENUM80,, 30
Assign new numbers to the whole program starting from the
line# 80 with the increment of 30 in line numbers.
. RENUM 150, 70, 50
24 NOT FOR SALE - PESRPAssign new numbers to lines from 70 to the end of the program
such that the new sequence will start from 150 (i.e., line# 70
will be renumbered to 150) and an increment of 50 is made for
each next line.
2.9.13 RMDIR Command
This command is used to remove/delete a directory from the disk.
Syntax:
RMDIR pathname
Interpretation
The pathname is the path of an existing directory which should
not exceed 63 characters. The directory to be deleted must be empty
otherwise an error message will appear.
Example
RMDIR “D:\GOODS\INVENTORY”
Deletes the subdirectory INVENTORY of the directory GOODS.
2.9.14 RUN Command
This command is used to execute the program currently in memory. If
the program is not in memory, it first load and then run it
‘Syntax:
. RUN [line number] [, r]
© RUNGfilename [,
Interpretation
By default the RUN command starts executing the program
from the beginning. However, if the line number is specified then the
execution of the program starts from that particular line number.
When the filename is specified with RUN command, it closes all
opened files and deletes all memory contents before loading and
executing the specified file from the disk, The r option is used to keep
all data files opened during the execution of RUN command.
Example:
RUN “table.bas”, r
Executes table.bas without closing data files
If you are using the speaker on the compute, please note that executing the
RUN command will nem off any sound that is currently rnining and will reset to
Music Foreground.
2.9.15 SAVE Command
This command is used to save the program on the disk for later use.
Syntax:
* SAVE filename, [, a]
. SAVE filename, [, p]
25 NOT FOR SALE - PESRPInterpretation
By default GW-BASIC saves the file in a compressed binary
format. If the option [a] is specified, the file is saved in ASCII format.
The option {[p]saves the file in an encoded binary format (protected
format). We can not list or edit a file saved in protected format,
however it can be executed.
Examples
© SAVE “matrix.bas", a
Saves the file matrix.bas in ASCII format
© SAVE “matrix.bas”, p
Saves the file in encoded binary format
2.9.16 SYSTEM Command
. This command is used to exit from GW-BASIC and return to
operating system environment.
ing
SYSTEM
Example
SYSTEM (Type in direct mode)
2.9.17 LIST Command
' This command is used to list all or part of the program currently in
memory to the printer.
LLIST [line number] [-line number]
LLIST {line number-]
Interpretation:
GW-BASIC always returns to command level after a LLIST is
‘executed. The line range options for LLIST are the same as for LIST.
2.9.18PRINT Command
‘This command is used to print data at the printer.
tax:
LPRINT [list of expressions) [5]
Interpretation:
lise of expressions consists of the string or numeric expressions
separated by semicolons. string expressions is a string literal or variable
consisting of special formatting characters. The formatting characters
determine the field and the format of printed strings or numbers.
This statement is the same as PRINT, except that output goes
to the printer. For more information sbout string and numeric fields
and the variables used in them, sec the print statement. The LPRINT
statement assumes that the printer is an 80-character wide printer. To
26 WOT FOR SALE - PESRPreset the number of characters that can be printed across the printed
page (assuming that the printer is wider than 80 characters), see the
WIDTH statement.
am 9.19 ‘CONT Command
* This command is used to continue program execution after a break.
‘Syntax:
CONT
Interpretation:
Resumes program execution after CTRL-BREAK, STOP halts
a program. Execution continues at the point where the break
happened. If the break took place during an INPUT statement,
execution continues after reprinting the prompt.
CONT is useful in debugging; in that it lets us set break points
with the STOP statement, modify variables using direct statements,
continue program execution, or use GOTO to resume execution at a
particular line number. If a program line is modified, CONT will be
invalid.
2.10 BASIC Statements
Here are some commonly uséd statements of BASIC language.
2.10.1 END Statement
This statement is used to terminate program execution, close all files
and return to the command level.
Syntax:
END
2.10.2 REM Statements
This is a non-executable statement and is used to add explanatory
remarks in the program.
© REM [remarks]
. * [remarks]
10 REM This program calculates the average of two numbers
20 15
30 b= 25
40 avg = (a +b) /2
50 * Display the average
60 PRINT “Average = “;
70 END
In this program line# 10 and line# 50 are non-executable. The
BASIC interpreter does nothing to these lines; they are not translated
27 (NOT FOR SALE - PESRE
avg241
to machine language during the translation process. The REM
statement however increases the readability of the code and helps in
‘modifying, understanding and debugging the program
2.10.3 STOP Statement
This statement is used to terminate program execution temporarily,
and return to command level.
‘Syntax:
STOP
Interpretation:
STOP statements may be used anywhere in a program to terminate
execution of the program. When a STOP statement is encountered in the
program, the following message is printed:
Break in line nnnnn
Unlike the END statement, the STOP statement does not close files.
GW-BASIC always returns to command level after a STOP is executed.
Execution is resumed by issuing a CONT command,
Fig. 2.8: Example of CONT Command
OPERATORS IN BASIC
Operators are symbols which are used to perform certain operations on data.
These include arithmetic, relational, logical, and assignment operators.
2.11.1 Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations on
values (numbers). The GW-BASIC defines the following standard arithmetic
operators:
: ] Algebraic BASIC |
Operation Erato Expression _| Expression
Addition + atb atb
Subtraction = ab a-b
28 NOT FOR SALE - PESRPMultiplication * axb ab
Division 7 a/b a/b
7m am a*n
‘Negation = “a a
Modulus MOD aMODb aMODB
Integral Divi —a\b a\b
The use of first six operators is straightforward. The last two operators
are modulus (also called remainder operator) and integral-division. Contrary
to the division operator which returns the quotient, the modulus operator
returns the remainder of an integral division. For example, if a, and b are two
integers having values 8 and 3 respectively, then the express a MOD b will be
evaluated to 2, which is the remainder of integral division. The integral-
division does not allow a fractional value in the quotient. It always returns the
quotient as a whole number. For example, the result of the expression a \ b
(for above two variables a and b) will be 2.
2.11.2 Relational Operators
Relational operators are used to compare two values. These operators
always evaluates to true or false. They always produce a non-zero value (in
most cases 1) if the relational expression evaluates to true; or a O value if the
relational expression evaluates to false. There ate six basic relational operators
in BASIC. Suppose a, b, and e are three integer variables having values 123,
215 and 123 respectively then:
Operation Symbol | Expression | Evaluation
| Equal to (comparison) = a=c | true (non-zero)
Less chan. z b a>c__| false (cero)
Less than or Equal to <= a<=b | true (non-zero)
Greater than or Equal to | >= | b<=a__| false (zero)
‘Not Equal to <> | a PRINT USING "##.##"; 85
> 0.85
> PRINT USING "###.##"; 254.753
37 NOT FOR $ALE -PESRP> 254.75
> PRINT USING "##.##" ;10.2,5.3,66.789,.234
> 5.30 66.79 0.23
In the last example, three spaces were inserted at the end of the format
string to separate the printed values on the line.
‘A plus sign at the beginning or end of the format string causes the sign
of the number (plus or minus) to be printed before or after the number.
‘A.comina to the left of the decimal point in the format string causes a
‘comma to be printed to the left of every third digit to the left of the
decimal point. A comma at the end of the format string is printed as
part of the string.
1 Fill in the blanks:
(i)
i)
(ii)
(iv)
ww)
(wi)
(vii)
(viii)
(ix)
()
BASIC stands for :
BASIC was developed by John Kemeny and Thomas Kurt in
at Dartmouth College, USA.
GW-BASIC shows a(n) ‘message, when loaded.
In mode, the commands are executed as they are typed.
Every statement in a BASIC program is preceded by a
A GW-BASIC program line can not have more than
characters.
There can be maximum. lines in a GW-BASIC program.
The defeult extension of a GW-BASIC program is :
The words which have pre-defined meaning programming
language are called
is an example of a non-executable statement.
2 ‘Choose the correct answer:
@
Gi)
(ii)
(iv)
GW-BASIC can operate in:
(a) Onemode* (b) Two modes
(c), Three modes (a) Several modes
The maximum length of a variable name in GW-BASIC is:
(@) 31 ) 32 on @ 45
Iftwo or more statements are written on a line, they must be separated
bya:
(@) Colon (6) Semicolon —(@) Comma (4) Hyphen
Which of the following is a type declaration character for integer
variables?
(a) ! (b) % () # @ $
38 NOT FOR SALE -PESRP