Computing With Basic: Problem Solving Wtih Structure And Style [1st Edition/Revised] 1642872598, 9781642872590

This book introduces basic progamming, Language and solving. See Also: http://ncbabooks.com/view/35/COMPUTING+WITH+BASIC

338 58 21MB

English Pages 231 Year 2020 [1995]

Report DMCA / Copyright

DOWNLOAD FILE

Polecaj historie

Computing With Basic: Problem Solving Wtih Structure And Style [1st Edition/Revised]
 1642872598, 9781642872590

  • Commentary
  • TruePDF

Table of contents :
COVER......Page 1
PREFACE......Page 6
CONTENTS......Page 8
CHAPTER 1 COMPUTER : AN INTRODUCTION......Page 12
CHAPTER 2 PROBLEM-SOLVING ON A COMPUTER......Page 30
CHAPTER 3 GETTING STARTED IN BASIC : GENERAL INTRODUCTION......Page 54
CHAPTER 4 CONSTANTS, VARIABLES, EXPRESSIONS, & STATEMENTS......Page 66
CHAPTER 5 INPUT/OUTPUT STATEMENTS......Page 81
CHAPTER 6 CONTROL STATEMENTS......Page 97
CHAPTER 7 SUBSCRIPTED VARIABLES......Page 136
CHAPTER 8 FUNCTIONS AND SUBROUTINES......Page 158
CHAPTER 9 FILE PROCESSING IN BASIC......Page 194
CHAPTER 10 GRAPHICS PROGRAMMING......Page 206
INDEX......Page 220

Citation preview

COMPUTING with BASIC [PROBLEM SOLVING WITH STRUCTURE AND STYLE]

"This page is Intentionally Left Blank"

COMPUTING with BASIC [PROBLEM SOLVING WITH STRUCTURE AND STYLE]

SS ALAM . Department of Mathematics, Indian Institute of Technology Kharagpur 721 302 INDIA

SK SEN Supercomputer Education & Research Centre Indian Institute of Science Bangalore S60 012 INDIA

New Central Book Agency (P) Ltd 8/1 Chintamoni Das Lane, Kolkata 700 009 INDIA

COMPUTING

WITH

BASIC

First Published : 1995 With Additions : March 2008

Copyright© reserved by SS Alam and SK Sen Exclusive rights reserved by New Central Book Agency (P) Ltd, for publication, distribution and export. All rights reserved. No part of this publication in general and the diagrams in particular may be reproduced/transmitted in any form or by any means, electronic, mechanical, photocopying, recording or any information storage and retrieval system, without the prior written permission of the Publisher.

Publisher & Typesetter

New Central Book Agency (P) Ltd 8/1 Chintamoni Das Lane, Kolkata 700 009

Printer

New Central Book Agency (P) Ltd Web-Offset Division, Dhulagarh, Sankrail, Howrah

Project Team

Prabir Ghosh, Bikash Mookherjee

Cover Designer

ANGIK

Cover Printer

Biswanath Studio 3 Garanhatta Street, Kolkata 700 006

I SBN:978 1642872590 ISBN: 81-7381-0830-4

Price : Rs 195.00 [Rupees One Hundred and Ninety-five only)

This book introduces the BASIC programming language and computations in science and engineering using this language. It is mainly intended for the undergraduate in engineering, science, and mathematics and can be used as a text by selecting topics pertinent to a given curriculum. To gain practical experience, any such course should be, however, supplemented with laboratory work. It can also be used as a reference for anyone engaged in computation with a digital computer. Besides presenting the digital computer and its features with a chronological account, we introduce broadly, in Chapter 1, types of programming languages and their scope. Although how to go about solving a problem on a digital computer is discussed in detail in Chapter 2, this is often integrated with various algorithms in the other chapters. Chapter 3 is devoted to c.> general introduction of the BASIC programming language including how to run a BASIC program on a computer or through a terminal. Detailed syntactical aspects of the language such as those of BASIC constants, variables, expressions, and tnput/output and control statements, functions and subroutines form the theme of Chapters 4,5,6,7, an.d 8. These aspects have been profusely illustrated ·with examples. Chapter 9 is an indepth presentation of file management with examples drawn from IBM PC based as well as DEC 10 based systems while Chapter 10 concentrates on microcomputer graphics. While worked-out examples illustrate the text wherever needeed, the exercises at the end of each chapter are intended to aid the reader in a self-assessment of his understanding. There exist several books on the BASIC programming language in the market. This book differs from all these books both in the depth of treatment of the subject matter as well as in generality of presentation to a considerable extent. Principles of good programming (namely, designing a program in a top-down modular fashion, coding with structures, and programming with style) have been emphasized throughout the text. Programs have been written using structures and good programming style. The readers of this text will learn to write programs that are readable, efficient, and well-documented. Thus, they will be exposed to the principles of good programming as well as the specific rules of BASIC. The stress has not been much on the language of a particular machine or oriented towards the use of only a specific computer. It has been, more importantly, on computing on any machine. Certainly a text book of this type cannot be written without deriving many valuable ideas from several sources. We express our indebtedness to all the authors, too numerous to acknowledge , individually, from whose specialised knowledge we have benefited. We are deeply obliged to Prof. G. P. Bhattacharjee of I.LT., Kharagpur, for his constant help and encouragement throughout the preparation of the manuscript. It is our pleasure to acknowledge the.assistance received from various colleagues and students from I.LT, Kharagpur, over the years the manuscript has taken to develop. Finally, we would like to express our sincere appreciation to Mr. Arunabha Sen, Director, New Central Book Agency, for his courteous cooperation and helpful .understanding. Suggestions and comments for improvement of the book are always welcome and shall be gratefully acknowledged.

S.S.Al.AM Department of Mathematics Indian Institute of Technology Kharagpur - 721302, India.

S. K. SEN

Supercomputer Education and Research Centre Indian Institute of Science Bangalore - 560012, India.

"This page is Intentionally Left Blank"

CONTENTS b

lb

b

CHAPrER lb

CHAPrER2

CHAPrER3

lb

lb

COMPUTER :. AN INTRODUCTION

l

1.1

Definition l.l.l Types 1.2 Chronological Account Components for Computations 1.3 1.3. l Hardware 1.3.2 Software 1.3.3 Humanware 1.3.4 Firmware 1.4 Programming Languages Exercises PROBLEM-SOLVING ON A CCJMPUTER

l l 2 5 5 10 15 15 .15 17 19

2.1 2.2 2.3 2.4 2.5 2.6

Introduction Problem Analysis Algorithm Development Flowchart Description of Algorithms Top-Down Program Design Structured Design Approach 2.6.l Sequence structure 2.6.2 Selection structure 2.6.3 Repetition structure 2.6.4 Five basic unstructures 2.7 Pseudocode 2.8 Program Coding 2.8. l Structure of a basic program 2.9 Sample Program 2.10 Entering a Program into a Computer 2.11 Debugging/Testing/Executing a Program 2.12 Programming Style 2.13 Program Structure : Modular Programming Exercises GE'ITING STARTED IN BASIC : GENERAL INTRODUCTION

19 19 20 22 '25 27 28 28 28 30

3.1

43 43 44 45 46 46 50 50

3.2 3.3

Introduction to Basic 3. 1. l BASIC character set Introduction to Timesharing 3.2. l Keyboard Running a BASIC Program 3.3. l Logging in 3.3.2 Loading a program from an auxiliary storage device 3.3.3 Running a program

31 33 33 34 35 36 37 39 41 43

b

b

il:ii

CHAPTER 4

CHAPTER 5

CHAPTER6

il:ii

b

b

3.3.4 Lisitng a program 3.3.5 Editing programs 3.3.6 Logging out 3.4 Sample Terminal Session Exercises CONSTANTS, VARIABLES, EXPRESSIONS, AND ASSIGNMENT

50 50 51 52 54 55

4.1

Constants 4. 1.1 Numeric constants 4.1.2 String constants 4.2 Variables 4.2. l Numeric variables 4.2.2 String variables 4.3 Expressions 4.3.1 Arithmetic expressions 4.3.2 Relational expressions 4.3.3 Logical expressions 4.4 Statements 4.4.1 Assignment Statement 4.5 Mixed-Mode Arithmetic Exercises INPUT/OUTPUT STATEMENTS

55 55 56 56 57 58 58 59 60 61 63 63 65 66 70

5.1 5.2 5.3 5.4

Input Statement READ and DATA Statements RESTORE Statement PRINT Statement 5.4. l PRINT statement rules 5.5 Additional Output Control : TAB and SPC Functions 5.6 PRINT USING Statements 5.6.1 Numeric field specifications 5.6.2 String field specifications 5.6.3 LPRINT statement 5.7 GET Statement Exercises CONTROL STATEMENTS

71 72 72 73 76 77 77 78 81 82 82 83 86

6.1 6.2 6.3

86 87 90 94

6.4 6.5

6.6

GOTO Statement (Unconditional Branching) ON GOTO Statement (Multiple Branching) IF /THEN Statement (Conditional Branching) 6.3.1 Multiline statements and multistatement lines 6.3.2 Selectlni; from several alternatives 6.3.3 Minimising the use of GOTOs FOR/NEXf Statement FOR/WHILE and FOR/UNTIL Statement 6.5.1 FOR/WHILE Loop 6.5.2 FOR/UNTIL Statement Structured Programming 6.6.1 Control structures using IF/THEN and GOTO statements

~

100 101 106 107 109 110 . 110

6. 7 6.8 i!:i CHAPI'ER 7 b

6 CHAPI'ER 8 i!:i

i!:i

i!:i

CHAPI'ER 9

b

CHAPIER 10

r0

Program Control Statements : The STOP and the END statements Some More Illustrative Examples Exercises SUBSCRIPIBD VARIABLES

111 111 117

7.1 7.2 7.3 7.4

Introduction DIM Statement Reading and Printing of Arrays Matrix Operations 7 .4.1 Matrix Arithmetic 7.4.2 Matrix input/output 7.4.3 Special matrices 7.5 Vrctors and MAT Statements Exercises FUNCTIONS AND SUBROUTINES

123 126 128 133 133 134 137 138 139 144

8.1 8.2

Built-in Functions User Defined Functions 8.2.1 Single-line user defined function 8.2.2 Multiline user defined function 8.3 Subroutines 8.3.1 ON GOSUB Statement 8.3.2 Data Menu driven Programs 8.3.3 Named subroutines with arguments Exercises FILE PROCESING IN BASIC

144 154 154 156 161 170 172 174 177 180

9.1 9.2

Data Files Creating a File 9.2.1 Creating a sequential file 9.2.2 Reading a sequential file 9.2.3 Modifying a sequential file 9.2.4 Modifying a sequential file using arrays 9.2.5 Merging sorted sequential files 9.3 Random File 9.3.1 Writing a record to a random file 9.3.2 Reading a record in a random file 9.3.3 Storing and readinng numeric data 9.3.4 Modifying a random file 9.3.5 Indexed files Exercises GRAPHICS PROGRAMMING

180 180 181 182 183 184 185 186 186 187 187 188 189 190 193

10. l 10.2 10.3 10.4

193 194 195 199 203 204

Introduction Colouring Individual Pixels Drawing Geometric Figures Printing Text on a Graphics Screet Exercises INDEX

123

"This page is Intentionally Left Blank"

COMPUTER : AN INTRODUCTION

1

1.1 DEFINITION The literal meaning of the term computer is any machine capable of arithmetic calculation, namely, addition, subtraction, multiplication, and division. But more widely implied meaning of the term computer, usually understood to be a digital computer, is a machine which possesses the following properties: 1. The machine is electronic, that is, it achieves results through movements of electronic pulses rather than the physical movement of internal parts. However, magnetic disks/drums/tapes as well as printers may be parts of a computer, where physical movements exist. 2. It has a storage that can store program (that is, an ordered set of instructions to the machine) fed through its input devices. The program, during execution. uses data, that is, the input information needed by the program, that are also fed through an input device. 3. It is able to change the course of program execution, that is, the machine while executing the instructions in the program in a s ....-quence can change the course of execution of tbe instructions (branch) because of a decision based on data stored in its internal storage and/ or on the results of one or mor~ arithmetic/logical operations (a logical operation is one whose operands are boolean and which produces a value true or false).

1.1.1 Types There are two major types of computers, namely, analog computers and digital computers. A computer that (i} measures continuous physical quantities such as voltage. temperature. pressure, and shaft rotations, (ii) converts each quantity to analogous decimal digits, and (111} then realises an arithmetic or logical operation is an analog computer. As an example. consider the circuit in Fig. 1.1. We can set the resistance r of the resistor R, measure the voltage v by the voltmeter V and can realise the result of division as the current i (that is, i = v /r) me.asurerl by the ammeter A. A computer that operates directly on digits that represent either discrete data or symbols is a digital computer or often referred to as a computerwhich has been defined earlier. We have DEC 1090 computer system manufactured by the Digital Equipment Corporation, Fig. 1.1 Analog Computer realising division U.S.A.

2

COMPUI1NG WI1H BASIC

An analog computer gives a limited accuracy (in computation), say, 0.01 percent, because of the inherrent errors involved In measuring physical quantities while a digital computer can give a desired accuracy, say, 0.00001 percent, in computation if sufficient physical (hardware) resources are provided. A general purpose digital computer can solve a wide range of problems ·and is much more versatile than analog computers. The immense importance of digital computers is due to their ability to store a large volume of information and to perform computations at a tremendously high speed. However, since a digital computer processes data sequentially, it is slower than an analog machine. A combination of the digital and analog machines is often called a hybrid computer. In the following sections, we will discuss about digital computers only.

1.2 CHRONOLOGICAL ACCOUNT The persent day computer owes its existence to many concepts developed over decades. However, the idea of using mechanical aids (such as Abacus) for calculation is very old. Till about early 1940s, computers and storage media such as punch cards were essentially comprised of electrical and/or mechanical components. There existed no serious impact of computers on scientific and engineering computation. Mid 1940s onwards, the computers called first generation computers made of electronic valves started their presence felt by the scientists and engineers. The first of these, ENIAC (Electronic Numerical Integrator and Calculator) was completed in 1946 by John W. Mauchly and J. Presper Eckert at the Moore School of Electrical Engineering of the University of Pennsylvania. It was about thir~ times faster than the earlier computers. The first computer to use the stored program concept , namely, EDSAC (Electronic Delay Storage Automatic Calculator), was developed in 1949. The first generation computers produced during 1940-58 were bulky, used great amount of electric power, generated a great deal of heat, and were not reliable. Some of them could store programs internally and received their input data from paper ta!)e or punched cards. Their computation speed was in the range of 3000 to 5000 additions per second. With the advent of transistors dwini:, late 1950s, the computers replaced the bulky electronic valves by transistors thus making their sizes smaller with increased reliability and computing power. Such transistorised computers are known as second generation computers. The first of these, IBM 7090, was introduced in 1958. Many such computers were built and marketed during 1958-64. These computers were smaller and less expensive, required less power, generated far less heat, and were more reliable than their predecessors. They had calcuating speed ranging from 2,000 to 50,000 additions per second with an average speed of around 10,000 additions per second. Built-in error detecting devices, faster input/output, greater capacity, faster storage, and ability to transmit information to other computers at great distances over telephone lines were some of the special features of these computers. One of the technologies refined with second-generation computers was magnetic tape storage, originally Introduced with first-generation computers in the mid-1950s. Data was recorded on magnetic tapes in much the same manner as music is recorded on your home tape recorders. Magnetic tape offered users the ability to store vast amounts of data on a medium that was readily accessible. In late 1950s, it was felt that the physical size of a transistor had no bearing on its ability to represent the on/off state; a piece of silicon (far smaller in size) could do the same job as well. In 1958, the first Integrated Circuit (IC) was produced which is a device that incorporates all the capabilities of many transistors and other circuit components consisting of diodes, resistors, and capacitors in one tiny chip of silicon. This chip could be as small as 1I16 of a square inch, weighs a small fraction of one ounce, requires only a trickle of power, and its production cost is very low. The list of instructions to solve a particular problem coded in the same way as input data was stored initially in the computer. Then each stored instruction is taken and execution is carried out by the computer. This is known as the stored program concept which was first introduced in EDSAC. Punched paper tape was used to transmit data into data storage unit of the computer.

COMPl.JIER : AN INI'RODUCITON

3

The computers using integrated circuits (ICs) were termtd as third generation computers. IBM 360, introduced in 1964, is generally accepted as the first of this generation of computers. These computers had increased arithmetic capability (as many as ten million additions per second) and reduced size and cost. Minicomputers appeared in the market. Its compact size and relatively low cost were a boon to small companies and universities. Nevertheless, sales of the larger computers, now being called mainframes, also increased rapidly, led by IBM's innovative System 360. The computer age had clearly arrived. Minicomputers such as the PDP-11 system are smaller than conventional computer systems yet offer comparable processing capabilities at a competitive price. Minicomputers were originally introduced in 1965 by Digital Equipment Corporation but attained their widespread acceptance when programmers discovered their limited but effective processing potential. They offer the same operational capacities of larger systems but to a lesser degree. A major hardware unit to complement third generation computers was the magnetic disk. The magnetic disk was a significant change from all previous storage devices, as it permitted the randoin access of data held onto its surface. Previously, data could only be strored on a sequential basis, and an individual record could be accessed only after all records before it had been scanned. Using disk storage techniques, programmers found that it was possible to access a specific item of data directly, without involving other records in that file. Now computer files could be composed of organised series of records, with any record independently accessible via magnetic disk. Major breakthroughs were also achieved in the transmission of data between computer systems and users located many miles apart.Computerised data are now transmittable over telephone lines and microwave facilities to remote computer centres, thereby providing high-speed processing support to widely distributed organisations. The term telecommunications was introduced to describe activities related to the transmission of computerised data over communications lines. The modern computer industry has also incorporated satellites into its data communications services. Many computerised networks use satellites to •apidly transfer data between continents and widely dispersed corporate headquarters. Satellite communications represent some of the most sophisticated telecommunications activities in use today. During 1970s, microprocessors which are large scale integrated circuit (LSI) chips were introduced. Microprocessors are themselves very small computers and capable of performing arithmetic and logical operations. In 1979 a microprocessor chip representing the equivalent of 68,000 transistors was introduced by the Motorola Corporation. Within two years a memory chip approximately 1 /2-inch square and capable of storing 72,000 items of data was introduced by IBM. The fourth generation includes (i) large computers that are much faster, much less expensive and of much greater data processing capability than equivalent sized third generation computers, (ii) a multitude of relatively inexpensive minicomputers (actually first introduced in the third generstion), and (iii) even further miniaturised computers, called microcomputers (or home computers or personal computers). The fourth generation computers have increased the man-machine interaction capabilities and speed. It is such microminiaturisation that completely revolutionised computing in 1980s, and made possible the development of personal computers such as Apple, TRS-88, IBM PC, Commodore and the like, bringing them to people's homes. The microcomputer can be used for both business and home entertainment activities. {This was possible only by the development of the very large scale integrated (VLSI) circuit chips.) Many types of business and en~ertainment software are commercially available for microcomputers. A principal language used with microcomputers is BASIC. Microcomputers offer tape and disk storage capacities, also. Small tape cassette devices offer the sequential storage of data on magnetic tape. Small flexible disks, referred to as floppy disks or diskettes, support disk storage operations on microcomputers. These smaller systems also possess cathode ray tubes (CRTs) with colour display capabitities and many types of printing devices. The very large scale integration (VLSI) technology, on the other hand, also made poosible the development of Cray, and Cyber supercomputers. Supercomputers can perform over 100 million operations every second. The Institute for New Generatiun Technology, formed in 1982 in Japan, has taken lead in developing the next generation of computers. The .fifth generatj.on of computers or the knowledge processing systems, as they are being called, greatly modifies the Von Neumann design of the four generations of computers. There are parallel architectures, new memory organisations, and programming languages. The fifth generation will stand apart not only due to its technology, but also because it is conceptually and functionally different from the first four generations. These will not be mere data processing machines, which are totally nonintelligent, but will be specifically designed for intelligent processing of knowledge. These will be intelligent computers that can be

COMPUfl.'XI WTTH BASIC

4

made to converse with humans in a natural language and to understand speech and pictures. These will be the computers that can learn, associate, make inferences, make decisions, and otherwise behave in ways which we have always considered the exclusive province of human reasonings. The hardware and software technologies through the electronic computer generations are presented in Tables 1.1 and 1.2. Table 1.1 : Hardare technology through generations Generation

Component

Main Memory (MM)

MM Cycle time

Peripheral storage

First (1945-55)

Vacuum tube

40 to 40000 ms

Magnetic tapes, drums

Late first (1955-60) Second (1960-65) Third (1965-70) Late third (1970-75) Fourth (1975-90) Fifth (Expected mid 1990s onwards)

-do-

Mercury delay lines, Electrostatic tubes, Magnetic drums Magnetic drums, Magnetic cores Magnetic cores

10 to 20 ms

-do-

0.5 to 2 ms

Magnetic tapes, drums, disks Magnetic Tapes, drums, disks -do-

Magnetic cores, LSI

0.2 to 1 ms

MOS, Winchester disks

.001 to .02 ms

-doLaser, magnetic bubbles - do-

MOS, Bubbles, Optical disks

.0002 to .001 ms

-do-

Transistor Hybrid circuits, Monolithic ICs Monolithics, MSI. LSI; VLSI VLSI Nonsilicon

2to !Oms

Table 1.2 : Sm'tware technology through generations Generation

Software systems

Speed

First (1945-55)

Subrouitne libraries, interpreters (essentially machine language) -do-, Assemblers, Compilers, Simple OS tessentially symbolic language) -do-, Multiprogramming and timesharing communication systems (networks) -do-

2 to40KIPS

Late third (1970-75) Fourth (1975-90) Fifth (Expected mid 1990s onwards)

Late first (1950-60)

Second (1960-65)

Third (1965-70)

Special features

Typical example_s__ ENIAC. EDV AC, SEAC, SW AC, IBM 701, 702, UNIVAC I IBM 650, 704, 705, 709, UNIVAC II, B 205, 220

100 KIPS

500KIPS

Interrupt systems, Virtual memorty, Microprogramming

1 MIPS

-do-

-do-

2MIPS

-do-

-do-, User friendly OS

50 -1000 MIPS

-do-

-do-, Knowledge processing PROLOG, LISP

500 -5000 MIPS or knowledge inferences per second

-do-

CDC 1604, 3600 IBM 7000, 1400, UNIVAC III, Honeywell 800 85500, CDC 6000, 3300 IBM 360, UNIVAC 1108, Honeywell 200 IBM 370, CDC Cyber 70, B 6700, Many minicomputers IBM 3081, AMDHAL 470, INTEL 8748 Japanese proposal

·~-------------------------------------

KIPS = 1000 instructions per second MIPS = 1000000 instructions per second

COMPUT'ER:ANINI'RODUCTION

5

1.3 COMPONENTS FOR COMPUTATIONS Now that we have some idea of how computers came into existence, let us discuss the elements involved in a computation. There are four basic elements involved in a computation on computer: hardware, software, humanware, and firmware.

1.3.1 Hardware .It is a general term used to represent the physical and tangible components of the computer itself, that is, those components which can be touched and seen. It includes: input device(s). storage devices (main and auxiliary memory). control ilnit (program controller), arithmetic-logic unit, and output device(s). The control and arihtmetic-logic units are usually housed in the same cabinet and are collectively referred to as the central processing unit (CPU). The flow of information in a digital computer is shown in Fig. 1.2: the arrows represent the paths that the information (instruction and data) talces within the computer.

AUXILIARY MEMORY

AUXILIARY MEMORY

.....--vi

vi

~

~

U.l

u. u.

U.l

INPUT DEVICES

u. u.

---+

...

;::)

a:

~

MAIN MEMORY

_...

;::)

a:

E-

;::) 0...

0...

---+

OlITPlIT DEVICES

E-

~

::i

0

~ ,',_...r··-··-~-··-··-.. -t-.., .._,, \ I



j

I

~

~

:

'

I I

! ',

!



j

ARITHMETIC

:

I I

LOOIC UNIT

1. ,,.'

!

,'

-j'

'j-

+

\

I

I I

: I I

~-----ti co:~oL ~-f----.J L.·-··-··-··-··-··-··-··j CPU

-

Instruction and Data Flow - - - - Control Signals

Fig. 1.2 Flow of information

Each component is interconnected with the other components but performs a specific task. The input device converts information from a form suitable to human beings to one usable by the computer. The control unit directs this computer usable information to the appropriate device of

COMPUTING W11H BASIC

6

the computer for processing. The memory unit stores the information as directed by the control unit. The arithmetic-logic unit performs arithmetic operations and conducts comparisons of stored information to make logical decisions. The control unit then directs the results of the processing to the output unit; it may also direct that the results be stored back in the memory for future use. The output device then converts the results of processing to a form easily understood by human beings. These components and their interaction are described as follows.

Memory The storage devices of a computer are used to hold many types of information. The main memory is used to store both programs and data. It is also used for holding intermediate and final results of a computation. The main memory can be visualised best as an ordered set of storage locations or cells (as shown in Fig. 1.3) uniquely labeled from zero and up. The label of a cell is called its address. Each of these cells (also called a word) is further broken down into what are known as bits. The word "bit" is an abbreviation of "binary digit". The bits are represented by the symbols 0 and 1 and are used to store instructions and data by their combinations. A group of bits (representing a data or an instruction) that form the basic information unit of the computer is called a word. Each cell repersents a word and may have a length of 16 bits, 32 bits, 64 bits, and so on. WORD

ADDRESS

BYfE

BYTE

0

1 ~

2

.,,

/

v

_/

BIT

3 4

Fig. 1.3 Computer memory locations

A computer word can also be defined in terms of what is known as bytes. A byte usually refers to a group of six to nine adjacent bits used to designate a single alphanumeric or a special character. The number of bits used to represent a character is called the byte length1 of the computer. For example, the alphabetic character A would be stored in an 8-bit byte as 11000001. A word may be formed using .two or more bytes, the most common being the four-byte combination. A two-byte word, obviously, contains 16 bits and a four-byte word 32 bits. To handle character data the programmer uses character handling instructions, while for numbers, number handling instructions are used. This is because the computer by itself cannot tell what the bits stand for. For example, the string of bits 11000101 would stand for the letter E or for the decimal number 197 depending on interpretation (character or number) or handling routine used. Memory capacities are measured in K bytes or K words, a K being equivalent to 1024 (2 10 ). Since a byte contains usually only 8 bits, it is clear that a 64 K-word machine has more capacity than a 64 K-byte machine. 1

Another common usage of the term 'byte• is the smallest number of bits accessible as a unit in the computer memory.

COMPUTER : AN INI'RODUCITON

7

The memory of early computers was usually built of magnetic cores but the modem computers invariably make use of the solid state materials called semi-conductors. Although these devices allow for a rapid retrieval of information stored in them, they are rather expensive. This is why most computers aiso incorporate external or auxiliary storage devices, such as the magnetic drum, magnetic disk. magnetic card, and magnetic tape. These auxiliary storage devices are used to store additional information that are required infrequently by the computer. Such devices are larger and less expensive but the access time to retrieve information is much larger.

Control unit The control unit has the coordinating role and links all other units in the system. Its main function is (i) to control transfer of information betweeen various storage devices and the inpput/ output devices, and (ii) to f~tch, decode, and control the execution of program instructions (stored in the memory). The storage locations specially designed to temporarily hold instructions or data (information) are called registers or, equivalently, CPU memory locations, and these have a very short access time. The memory address of the instruction to be decoded and executed is first placed in a special register, called location register/counter or, equivalently, program counter or instruction counter, from where it is transferred to the memory address register and a read operation is performed. that transfers a copy of the desired instruction from the memory into the memory buffer register. From the memory buffer register the instruction is transferred to the instruction register where it is decoded to determine from the instruction exactly what the computer must do. The control unit then causes the system to execute the instruction. In other words, the control passes odrers to the arithmetic-logic unit for computation/comparison and/or to the memory to obtain or store data, depending on what the instruction calls for. The operations, which require arithmetic or logical computations, are carried out using the special registers and circuits of the arithmetic-logic unit. The control unit is so designed that each time an instruction is moved into the instruction register, the location rnunter is automatically updated beforehand by the address of the instruction and when the execution of this instruction is completed, the location counter will contain the memory address of the next instruction to be executed. Modem computers allow some instruction overlap. If the instruction register can hold more than one word and the memory buffer is large enough, several instructions can be obtained at a time from memory and one can be decoded while another is being executed. It is even possible to execute several instructions in parallel, that is, simultaneously. However, one must be careful not to execute in parallel two instructions one of which depends on the other.

Arithmetic-Logic Unit The arithmetic-logic unit contains the necessary circuits, such as those for adders, multipliers, counters, comparators to perform various arithmetic and logical operations. It also contains a small set of registers, the most important being the accumulator in which the results of arithmetic and logical operations are kept. The operations receive arguments (operands) from one or more computer words found either in one of the arithmetic-logic registers (CPU memory) or in the computer main memory. For instance, an adder takes the data from two or more sources and performs addition; a counter usually counts the number of times an operation is performed; a comparator can compare two values and so on. The result of the operation can also be placed in a register or in a main memory location.

Buffers The operating speed ofinput/ output units is slower than main memory speed and much slower than the processing speed of the CPU. Therefore, the CPU has to wait till the entire data is read by the input unit. The efficiency of the computer can be substantially increased if the input/output and processing operations can occur at the same time. To achieve this, an interface unit called buffer is used. During processing, the data 1 s read into the buffer that can transfer the data to the main storage unit at high speed. If buffer units are provided at both the input and output ends, then all the three operations, namely, the input, process, and output operations may be performed simultaneously.

COMPUI1NG WITH BASIC

8

While the size of a main memory is large (compared to the CPU memory). a complete computer system requires the ability to store several orders of magnitude more data than that which can be stored in main memories. A computer, therefore, needs auxiliary (or secondary) storage devices which have large capacity but whose data may be accessed or altered only slowly in comparison with the speed of main memory. The movement of data between auxiliary memory and the rest of the computer is only via the main memory. That is, data may be transferred from the main memory to the memory buffer to an auxiliary storage device, or the process may occur in the reverse order. Since the auxiliary devices (and the "outside world" as well) are typically much ..;lower than main memory, large computers have one or more separate control units/small computers, called data channels, whose main job is to control the movement of data between the main memory and the auxiliary devices and the outside world. Three currently important auxiliary storage devices are magnetic tape, disk, and drum. We shall discuss each of these in tum.

Magnetic tape A commonly used auxiliary storage device is magnetic tape - a strip of iron mode coated plastic material. These tapes are similar to the audio tapes which are used so often these days. A tape reel may coritain 2400 feet of tape or less. In fact, magnetic tapes are not restricted to any one size; on many of today's microcomputers, magnetic tapes are no longer bigger than those in the portable cassette tape units. Information is stored on the tape by magnetising a set of spots in the iron oxide. The code used in storing information in tape is similar to that used in main memory. Digital information is written onto a magnetic tape by lining up the magnetic/spots domains in different directions to represent O's and l's. The tape passing under a tape (read/write) head has its magnetic domains lined up in one of two directions. For example, N-S direction might represent 0 and S-N direction 1. To read the tape, the polarity of magnetism is sensed by the tape head. A tape has several parallel tracks, usually the number of tracks is one more than the number of bits in a byte. One byte is written in a column, and the extra track gets a parity bit, chosen so that the number of l's in any column is an odd number. For exmaple, if 8-bit bytes are used, then a 4-byte word 01000001010011000100000101001101 would appear in four columns of a nine-track tape as shown in Fig. 1.4.



Tape motion direction

----------------------0 0 0 0 1

1

1

1

0 0 0 0 0

0 0

0 0 0 0 0

0 0

1

1 1

0 0 0

1 1

1

1 0 1 1

• -------------------------1

Fig. 1.4 Portion of a tape

The first eight bits O1000001 appear in the first column of Fig.1.4. Since there is an even number of l's, parity bit 1 is chosen. In the second column, there is already an odd number of l's, the parity bit 0 is selected.

g

COMPUI'ER : AN INTFIODUCITON

The magnetic tape provides relatively high speed input/output (compared to that of a card rec;ider which is no longer used) of data to a compu< ~r. However, its operation is strictly sequential. It cannot read or retrieve data randomly, it does not permit the immediate access to specific areas of information without examining each record.

~~~;~--

~~~:~~~~~I ~I~~~~~~ I~I~:~~~~~ J~ ~ ~ ~------#n

..__________\~~ INTER-RECORD GAP Fig. 1.5 A typical coded tape

The interr~cord gap (Fig. 1.5) is the starting and stopping space required by the read/write head of the tape drive and is usually 3 I 4 of an inch long. The set of records on the tape is called a file. Since interrecord gap is considerable, storage of many smali records may result in the collection of a large number of inter-record gaps which consumes more space than that requried by the records themselves. Tins is a wastage of tape space. It is, therefore, resirable that a record should be as large as possible (subject. of course, to the total length of the tape). The retrieval of data (information) from a tape is possible only in sequential fashion.

Magnetic disk Magnetic disk is a widely used auxiliary storage device. It is a flat circular disk coated with iron oxide. It appear!' like a phonograph record but with no grooves on the scrface. A disk pack is a set of disks stacked coaxially one above the other with a small separator between any two disks. The motor of the disk drive causes the disk pack to rotate at a constant speed of 1200 revolutions per minute. The disk drive contains a set of read/write heads which can move in and out between the disks as the disks rotate. Except for the top surface of the top disk and the bottom surface of the bottom J.+-i...;.......+L--¥-~-14-.;...i....i disk, information can be recorded on both sides of the disks that Track make up the pack. To facilitate storage/retrieval of information on/from a disk pack, each disk surface has its own number, 0, 1, 2, ... , k where k depends on the number of disks in the pack. Each disk surface is Fig. 1.6 Disk surface divided into a set of concentric circular tracks. Each track has a unique number ranging from 0 tom and is divided into sectors numbered from 0 ton (Fig. 1.6). As with magnetic tapes, the information here is stored using magnetic spots on these tracks. The group of all tracks with the same number on all surfaces of a disk pack is called a cylinder. The mechanism used to re< ·'./write from/ on the disk pack is called access mechanism Only one of the heads can be turned on at any one time, and, thus, only one track can be operated upon at one time. Each of the heads can both read and write but can do only one (read or write) operation at a time. In order to operate on a recording s11rface, the access mechanism moves to the track that is to be operated upon. When access mechanism moves, all the heads move in unison so that they are positioned at the same track on each of the recording surfaces. These tracks, which are said to make up one cylinder, then can be operated upon one after another without the access mechanism having to move to another setting. The storing of data in the cylinder saves time and allows for faster input/outpµt activity as the movement of the access mechanism constitutes a significant portion of the time needed to access and transfer data. Some disk devices are designed with an individual read/write head for every track on every surface.

COMPUTING WITH BASIC

10

Various Input/Output Devices The devices with which computers can communicate are many 'and varied. They are collectively called input/output (IO) devices or peripherals. Input : The peripheral devices used for input include (i) punched card reader (not used any longer). which can input a few hundred cards per minute, (ii) Keyboard (similar to a typewriter) for entering typewritten characters, (iii) optical reader for written text, (iv) magnetic ink reader for bank cheques, (v) microphone to permit sound to be input directly into the machine, (vi) sensors for temperature, pressure, volume, positions, etc. (used in physical/chei.1ical experiments). (vii) electronic clock to enter the time of'the day, (viii) power-fail instruments to tell the computer that the electrical power has failed, and only a small quantity of stored power exists with which to save any critical data. Output: Peripherals used for output are (i) line printer which can print a few hundred (up to a few thousand) lines of text per minute, (ii) video (monitor) screen as in a 1V to display written text or diagrams/pictures, (iii) plotter to draw graphs/picutres, (iv) speaker to permit the computer to output sounds such as spoken words/music, (v) effectors to operate valves, tum equipments/instruments on or off, apply a force, etc. Both input and output devices which can be connected to computers and used for both input and output include (i) magnetic disks (described earlier) for storage of a large amount of information, . (ii) magnetic tapes (described earlier) for storage of a large amount of information, the tapes are cheaper but slower than disks, (iii) a device which is an electronic equivalent to a magnetic disk, (iv) other computers. To communicate with IO devices, special instructions can b~ included in machine la..~·•ages. These instructions, which usually include a few bits to specify the peripheral for which ._:_a communication is intended, transmit information to peripherals and recieve information from peripherals. Another method of IO communication is to regard each peripheral device as a part of exec..itable (main) memory, each with its own address. Exchange of information with the device can be performed using the ordinary LOAD and STORE machine language instructions.

1.3.2 Software By definition, programs 1 are designed to direct the computer in all phases of processing. This rationale was evolved from Von Neumann's stored program concept that programs retained within primary (main) storage control the computerised processing of data. However, not every computer software serves the same purpose. Some programs provide instructions on how to handle a specific problem, while others are utilised by the computer itself. Thus, we may utilise one program to process the payments made by a company, whereas the computer may use another program to control the processing of a related group of programs. The word software is a general term used to describe all kinds of programs associated with a computer. 1

The finite set of sequenced instructions (written in a computer language) which direct the computer in its processing activities.

COMPUTER : AN INTRODUCTION

11

To assist in identifying the types of programs used with computerised data processing activities, computer software is generally divided into the two categories, namely, applications software and operational software.

Applications and Operational Software Applications software consists of programs written (by users) for solving specific problems, such as preparing pay bill, calculating the stress factors for a building structure, etc. Each of these programs can be used only for jobs of a particular type. Recently many such programs have been made commercially available under the name "program packages". These can be changed marginally to fit in individual needs and to meet the system requirements. Operational Software is totally different and helps the computer efficiently supervise processing. It is an organised group of interrelated supervisory programs that control processing and define the processing potential of a computer system. It is the operational software of a computer system which defines what and how things are processed. Thus, in effect, the operational software of a computer system interacts with the applications software for a specific activity, which results in the actual processing of data. Because the concepts related to operational software are often difficult to digest by the beginning programmer, some further explanation is in order. It is the operational software of a computer system (or, as it is sometimes called, the operating system} which defines the processing potential of the hardware. Essentially, the operattpg system defines what processing activities the computer can support. For example, if a computer's operational software is only designed to handle computer cards, it will not support the online use of terminals, teleprocessing activities are out of question, and all CRTs attached to that computer's CPU will have no effect. Operating system programs are usually supplied by the computer manufacturer and, unlike applications programs, these programs are permanent residents of the computer system. The following functions are performed by some of the important operating system programs : 1. Load programs into the main memory from a secondary storage (say, disk) and execute them with input data supplied by the user. 2. Print messages for the operator and the programmer regarding the status of the program. 3. Perform job accounting by keeping track of who uses the computer and for how long. 4. Handle requests for input/output from executing programs. 5. Handle the collection of data from teiecommunications lines (in a time-sharing system). 6. Schedule the slice of time to be allocated to each user's program (in a time-sharing system or a multiprogramming system). 7. Perform some routine processing of data such as sorting and copying the contents of one data set onto a specified device. 8. Maintain the store of programs on a mass storage device (say, disk) - adding programs to the store, deleting those no longer needed, and so forth. 9. Create and maintain named data files in secondary storage. 10. Attempt to recover from and/ or correct errors that may occur in any segment of the computing system. 11. Interpret the job set up and job control instructions specified by the programmer. It is possible to obtain hardware computer systems that are identical down to the last nut and bolt and radically alter their processing potential by equipping the systems with different types of operational software. Thus, depending on their operational software, some could be limited to a few tasks and others will support an expanded range of data processing activities. The point of this over simplification is that a computer system will only perform processing tasks which its operational software can support. Computer manufacturers offer many types of operational software for their computers. Each operating system equips a computer with specific processing capabilities which have been matched

12

COMPUTING WITH BASIC

against the operational needs of users. Some permit a compute!" to support the type of interactive processing activities which are suited to the BASIC language. The tem1 interactive processing describes the online processing mode where users interact directly with the computer, affecting processing on almost a line-by-line basis. Because of this online interaction, an interactive processing is sometimes referred to as the processing in conversational mode. Most BASIC programs are written and executed within an interactive processing environment. Again, the operational software necessary to support an interactive processing must be available within the computer system slated to support such processing activities.

Program Execution For operational software to be used properly, control languages have been developed. Thef'c control languages are often uniqe to a given system. One of the most frequently encountered control languages isjob control language (JCL). which is a representative of most control languages currently being used. JCL is composed of a set of complex ope.rational codes which, when put together in certain combinations, enables users to communicate with the computer's operating system and tell the computer which applicai:ion~ programs are to be executed. To observe how JCL, operational software, and applications software interact, we should examine how an interactive language like BASIC is used. As we know, BASIC permits users to be onl!ne durinp: processing. In order to establish the online communications link between their terminals and the computer, users must follow a special set of JCL procedures which are generally referred to as WGON procedures. The instructions constituting a LOGON procedure are drawn from the JCL used with that system. These control instructions establish that a particular terminal is requesting access to the computer and that the BASIC language will be used on an interactive basis. It directs the computer to ready the operational software needed to support the online use of BASIC. Any special requirements related to the BASIC programs to be processed will come from t. 1e JCL composing the.LOGON procedure. The opposite of the LOGON procedure is the WGOFF procedure, which ls used when a user wishes to conclude a processing session. The JCL instructions constituting the LOGOFF procedure (1) cancel the existing online status, (2) stop Interactive processing activities, (3) permit the operat10nal software to tum towards other programs, and (4) prepare the computer for the next program. During the interactive processing of BASIC programs, the combined use of JCT. commands and operational software is also evident. The successful completion of the LOGON procedm ._ ~l"lables the user to start inputting the source program The source program is the term used to describt- ~~e program written by the users. Each statement of the source program is entered on an Individual basis via the terminal's keyborad. When the entire program has been input, the user may elect to run the program by keying the appropriate JCL command. The execution of the source program is accomlished by using a special program within the operating system. This program, referred to as a compiler, converts the source program into the machine language program, the only language the computer can utilise to actually execute a program. BASIC was used to simplify the preparation of software by humans, but it must be converted to machine language to undergo execution. It is the compiler which converts the source program written in BASIC to its equivalent machine language program for actual processing by the computer. Compilers exist for many currently popular languages, assisting in their conversion and execution. An attractive feature of compilers is their facility to check for errors in statements composing the source program. Compilers scan program statements and ensure that each statement was written according to the rules associated with that language. The failure to observe these rules will cause the processing of that program to stop. The computer's operational software will cancel the program and direct that the source of that error be output. These outputs are helpful in correcting the program errors. This correction process is sometimes referred to as debugging, as the programmer attempts to remove errors, or bugs, from the source program.

COMPUTER : AN !NTRODUCTION

A complier often associated ·with the conversion of interactive lacguages such as BASIC is the interpretive compiler or interpreter. The interpretive compiler converts each statement of an interac-

tive program into machine instructions as it enters the computer. With BASIC, each program statement is checked for errors by the interpretive compiler before conversion into machine language. Errors uncovered by an interpretive compiler are immediately output, making possible their rapid correction. The interpretive complier differs from other compilers in that it converts programs on a line-by-line basis, rather than accepting and converting the entire program as one large unit. Both types of compilers are part of a computing system's operational software. Canned Software In the past, many organisations preferred to have all their applications software written in-house, believeing that the tlnal product would be more suited to their needs. Recent increases in software development costs have led many organisation to reevaluate this position. Although hardware costs have gradually declined, the costs associated with programming personnel have risen dramatically. It is the cost of quality programming staff that has increased the expenses related to extensive program development. As an alternative to writing in-house software, many organisations are now considering the purchase of canned programs. The term cam .ed program defines commercially available software that handles one particular type of application. Canned programs are now readily available for almost every business application and many personal applications as well. Canned programs may be purchased for the processing of employees payrolls, amounts receivable related to credit cards, inventory control in warehouses, the analysis of economic conditions and budgets, and medical record keeping. On a personal b2.sis, canned software exists to project astrological forecasts, analyse your stock portfolio, prepare personal letters, record social engagements, and teach children how to spell. Most canned programs are prepared by computer manufacturers or private software houses that specialise in commercial applications. A trade-off exists between writing your own software or purchasing the canned software.

Online Processing Approaches Data may be processed in two Jifferent ways: in batches or on line. In batch processing, groups of data are accumulated over a specific period of time and them processed. This accumulation of data causes delays in processing. By contrast, online processing enables the direct handling of data and speeds up processing considerably. Online processing activities involve some form of telecommunication. Data is rapidly input to the computer for processing, thus speeding up the preparation of results. Each processing approach has its merits. When a delay in processing will not adversely affect an organisation's work, batch processu;g can prove effective and efficient. Hardware expenses related to batch processing systems are generally lower than online systems where more sophisticated devices are utilised. Online processing is designed to overcome potential delays. All l/O operations are online, permitting users to interact with their supporting systems. The weekly processing of a payroll is a good example of the batch processing approach. The organisation for which the payroll is prepared has seven days to accumulate and prepare the payroll data for processing. Once the data is collected, another week is available to process payroll data ar.d print employee paychecks. Compare these time constraints with those of a retail system where credit cards must be checked immediately. To ensure the accuracy of credit sales, clerks must have online access to customer charge card records. Using the online r!'tail system, charged sales are immediately verified and posted against the appropriate customer records. Without online support, this type of direct processing support. would not be po;;sible.

14

COMPffl'ING WITH BASIC

Time-sharing An online processing apporach which supports the use of an interactive language like BASIC is timesharing. Timesharing derives its name from the fact that multiple users can share the resources of a single computer at the same time. The operational software supporting a timesharing system allows each user to work with his individual program and to share on line I/ 0 operations of the system. Timeshareiug computers can support multiple users from one organisation or users distributed at distant regional offices. (On the other hand, virtually all microcomputers can interact with only one user at a time. These computers are called single-user machines.)

BASIC is ideally suited to a timesharing environment. Many users do not require, or want the expense of, full-scale computer support. Timesharing permits them to plug into a support system when necessary and receive online data processing services. They pay only for the services they use. Many beginners develop their initial skills at schools that use timesharing. BASIC is effectively used in, but not restricted to, timesharing. Student programmers may also use BASIC as the interactive language for their home computers. BASIC offers advantages to users in their operational environment. Timesharing provides a practical exmaple of the concept of multiprogramming, a processing environment created by a computer's operational software which permits the concurrent processing of multiple programs. Multiprogramming enables the computer to concurrently retain one or more programs in primary storage and process them as required. This technique takes full advantage of current computu processing speeds. By concurrently storing multiple programs, the computer can rapidly jump from one to another and process instruction sequences from within each program. The concept of multiprogramming must be compared against multiprocessing. Whereas multiprogramming involves a single computer, multiprocessing involves the simultaneous execution of two or more instn1ctions in two or more CPUs. Even with the impressive processing speeds, one CPU can execute only one instruction at one given instant. To execute two instructions from two separate programs simultaneously, two CPUs must be involved. Multiprocessing is normally associated with computer networks, where multiple systems at key locations interact with each other. These networks often support large cooperations, sharing the organisation's work load and distributing information to all levels of management. Often in a multiprocessing environment. supporting computers will utilise multiprogramming to increase their capacity for data handling and process of larger workload. Multiprogramming and multiprocessing techniques are often utilised by organisations which rent out computer services. These organisations, referred to as service bureaus, rent computer services, including software and hardware support, to users who do not want to own their own computer facilities. Users rent from service bureaus only those facilities they need and for services used. Service bureaus offer a wide range of services. Computer hardware may be leased from service bureaus. including computer systems or specialised 1/0 units. Service bureaus lease software, run user's software on their own computers and prepare results in a predetermined format, or input user's data, process it with their own software and return these results on a scheduled basis. These results may be printed and returned via messengers, or they may be telecommunicated to user's home office and printed in hardcopy form by the user for immediate distribution. Online processing activities are offered by many service bureaus and have become increasingly popular over the past few years. A drawback to the use of service bureaus is the possible loss of security, as your records and files are maintained in their computers and within their offices. It is the responsibility of the user to investigate a service bureau and determine whether it can provide adequate security as well as sufficient processing support.

COMPlffER : AN INTRODUCTION

15

1.3.3 Humanware The personnel which deals with the computer and its management put together is c'alled humanware. For a large scale commercial computer, the humanware might include the following personnel: software engineer, hardware maintenance engineer, systems analyst, programmers, compukr technicians/operators, and data entry operators. The software engineer is concerned with the developemnt of software packages, and the hardware engineer looks after the maintenance of computer components. The systems analyst studies the problem to be solved in detail and prepares solution and program specifications. The programmer prepares computer programs based on the specifications prepared by the systems analyst. The computer operator operates the computer syst.!m and should possess some knowledge of internal working of the entire system. The data entry operators enter the data/ir1formation (input) required by program(s) into a computer. 1.3.4 Firmware The firmware consists of programs which are usually implemented in hardware and which are permanent in some sense and can be changed usually by replacing hardware components inside the computers. Such a change is usually not desirable and more involved (difficult) than that in a software. These in-built programs consist of instructions to the computer. Sometimes trigonometric functions and other such details of common day-to- day use are also stored as programs (firmware) permanently inside the computer. Since software and firmware differ only in whether or not the programs can be changed easily, the two terms are not usually distinguished. A microprogram, however, has also been termed firmware. Microprogramming, as the name implies, is a type of programming. Microprograms directly control the sequencing of computer circuits at the detailed level of the single instruction. Organising the control hardware in a microprogrammed structure instead of a wired circuitry is economical if the computer has complex instructions. It is possible to produce an emulator, that is, a set of micropragrams by microprogramming. An emulator makes a given computer have the same appearance to a programmer as some other computer. This emulation allows the same computer to run programs written for either itself or the computer it is emulating at rea.sonable efficiency. Besides, microprogrammed special functions can be executed faster than those with software. However, micropragrams are slower than those using wired control circuitry. 1.4 PROGRAMMING LANGUAGES The language which is used in the communication between a human user and a computer is known as a programming language. Programming languages can be broadly classified into three major categories : i) machine language, ii) assembly (or symbolic) language, and iii) procedure-oriented language. The basic lowest level language for communicating with a computer is called the machine language. Every computer has its own (unique) machine language, and any communication with the computer must be in its machine language or a language that must be translated into its machine language. The functioning of a computer is controlled by a set of instructions. A finite ordered set of instructions to the computer is called a computer program or simply a program. Every proram has to be presented to a physical (hardware) computer in the machine language, the only

16

COMPUTING WITH BASIC

language that can be understood by a computer. A program in the machine language just consists of a sequence of large binary numbers which are known as numerical codes. For example, on a computer, a series of binary numbers, 00 11 1000 100 1 means "add a number stored in location 8 (the decimal value of 1000) to another number stored in location 9 (the decimal value of 1001) and store the result in location 8". (1be code number 0011 stands for the addition operation.) Another possibility is to hdve only one address in the instruction. TI1is type of instructions is known as .:me-address instructions. In this format, an implicit assumption has to be made regarding the location of one of the operands as well as the result. A general purpose CPU register, usually called the accumulator, may be used for this purpose. For example, on a computer the instruction 0011 1101 means "add the contents oflocation 13 (the decimal value of 1101) to the contents of the accumulator and place the result (sum) in the accumulator". Programming in a machine language is a very tedious process. Different machine codes are used for different computers. Each computer has its own machine language and, therefore, different computers need different programming for the same problem. Moreover, a programmer should remember codes for the different operations, functions, and locations. The numeric memory locations and the numeric codes are very difficult to remember. Since machine codes are machine dependent, they vary from computer to computer. To help reduce the programmer's burden, assembly (or mnemonic) languages were developed in the early 1950's. These languages use mnemonic (pronounced as ne-mon'-ik) codes and mnemonic addresses. In other words, alphanumeric symbols are used (to write a program) instead of numeric operation codes and addresses. For example, ADD or A is used as a symbolic operation code to represent 'addition' and SUB or S is used as a symbolic operation code to represent 'subtraction'. Memory locations containing data are given names such as GROSS, TAX, TOTAL, TIME, MONTH. Thus the symbolic language coding for the foregoing machine language two-address instruction might be ADD COST TAX and that for the one-address instruction might be ADD TAX But, since the physical computer can understand Instructions only If they are in its machine language, an assembly language program must be translated into the machine language before the program can be executed. This translation is done by a special machine language program (software) called an assembler or. equivalently, an assembly language translator. Programming in an assembly language is more convenient because the programmer does not have to keep track of as many details as with the machine language, which, In this case, are handled by the assembler when it translates the program. However, the programmer is still concerned with various details, such as indexing and storage locations, in addition to writing a complex sequence of instructions. Further, the assembly language is a machine-oriented language and hence an assembly program has to be different for different machines. The programmer should remember machine characteristics when he prepares a program. Moreover, the assembly language Is not much close to a natural language. Writing a program in assembly language is still time consuming and a tedious task. It is for these reasons that the languages known as high level languages emerged as some sort af a compromise between human languages ::md machine languages. A high-level language consists of a set of words and symbols using which the programmer can write a program, in conjunction with certain rules, similar to the English language. These 'almost-English' high-level languages are more user-centred than machine-centered; also, they are oriented towards the problem to be solved or procedures for solution rather than the computer (machine) instructions and, therefo-~. referred to as user-oriented or procedure-oriented languages. Some high-level languages are FORfRAN, BASIC. COBOL, PASCAL, ALGOL, C, and ADA, to name but a few. BASIC is the programming language you will learn in this book. Since the advent of microcomputers, which are often sold with BASIC included as part of the package, it has become a popular programming language in use today.

COMPUIER: AN JNIRODUCTION

17

. A high-level language program, like that in an assembly language, needs to be translated into the machine language program before being loaded into the memory of the computer and executed. This translation, often known as compilation, is performed by a large machine language program (systems software) called a compiler. The original program in high-level language is called the source program and its translated machine language form is called the object program. BASIC, however, is US\lally translated into machine language by means of a program called BASIC interpreter. The interpreter carries out each instruction of your program immediately after it has been translated. (A compiler, on the other hand, translates the entire program, before carrying out any of the instructions.) As a result, it is possible to have the computer execute partial BASIC programs. This will enable the user to see how his program is working before he completes it, if he so desires. The use of a high-level language, therefore, offers the user some very significant advantages over the use of the machine or an assembly language: Simplicity: A single instruction in a high-level language will be equivalent to several instructions in the machine language. Further, the terminology in high-level languages is 'almost-En_glish' and hence the languages can be easily learned and understood. Uniformity: The high-level languages have been standardized. Thus programs written in a high-level language, say BASIC, can be understood much more easily by all throughout the world. Machine Independence: A program written in high-level languages can generally be run on computers of different make with a little or no alteration. Dlaenoatic error detectabWty: Each high-level language has its own system or set of rules that governs the writing of instructions in the language. Hence before a program is translated and executed, the compiler checks each statement in the program for syntactical errors. All such errors are output, and translation is begun by the compiler only after all the errors have been corrected.

D 1. 2. 3.

Exercises

D

How do you distinguish among five generations of computers? (Include software and hardware aspects of all the five generations.) How do you define micro-, mini-, supermini-, medi-, large, and supercomputers with reference to storage, processing speed, hardware, and software architectures? A standard hardware configuration of a minimal computer, where a.1 are input/output devices, is

..

CPU

MEMORY (EXECUTABLE)

2

Data and Control Path Control Path

18

4.

5. 6.

7. 8.

9. 10.

11. 12.

COMPUI'ING WI1H BASIC

What is the missing name of the unit? What is its function? [Answer: Data channel or Input/Output processor or Input/Output computer. It permits overlapping of execution (by itselO of input/ output instructions with that of noninput/nonoutput instructions by the CPU.) Assume that all records are of same length of 400 characters and inter-record gap is 0. 75 inches. The character density of a magnetic tape is 1600 characters/inch, the length of the tape is 2400 feet, and the speed of the tape is 75 inches/second. Verify that the character storage or retrieval speed (in characters/second) of the tape will be 30000. Consider Exercise 4. Verify that the maximum storage capacity (in characters) of the tape will be l 152xl04 . A magnetic tape stores several records. Assume that the first record, that is, Record 1, has 200 characters, the second record, that is, Record 2, has 600 characters. In general, Record 1 has 200 characters if i is odd else it has 600 characters. Let the inter-record gap be 0. 75 inches. The character density of the tape is 1600 characters/inch, the length of the tape is 2400 feet, and the speed of the tape is 112 inches/second. Verify that the character storage or retrieval speed (in characters/second) of the tape will be 44800. Consider Exercise 6. Show that the maximum storage capacity (in characters) of the tape will be l 152xl04 . Let T be the number of time unit steps required by a parallel algorithm designed to utilise p ( > 1) processors. The speed-up factor of a parallel algorithm by comparison with its serial counterpart is defined by Sp= Ti/Tp ( ~ 1). For n operations each having k steps, show that the speed-up factor for a pipeline computer (that is, a computer where the execution of the first operation needs k time units, that of the first and second operations need k+ 1 time units, that of the first, second, and third operations need k+2 time units, and so on) is S = (nk)/(k+n-1) Consider Exercise 8. If n --t oc then show that S --t k. Compare functionally the magnetic tape and magnetic disk. How does main (executable) memory differ from secondary memory (disk, magnetic tape)? Distinguish between, high-level and low-level programming languages from user's point of view. Compare natural and formal languages.

PROBLEM-SOLVING ON A COMPUTER

2

2.1 INTRODUCTION

Computers may be used to solve many varied problems which are tedious and routine in nature. Today, there is hardly any field where computers are not used. For example, research organisations, business houses, industries, meteorologists, space technologists, communication departments, travel agencies, government departments, and educational institutions use computers extensively to solve their problems. Computer programming is a complex, creative task that demands a disciplined and organised apporach to problem solving. Students often assume that proficiency in one or more computer languages (such as BASIC, COBOL) is all that is required to be a good computer programmer. This is equivalent to assuming that proficiency in English ensures the success of a novelist or proficiency in draftsmanship insures the success of an architect. Before writing the program to solve a particular problem, the programmer must have a thorough understanding of the problem as well as an apporach to solve it. The programmer must be able to convert a problem to an algorithm. that is, a sequence of well-defined steps that can be carried out by a computer. In some cases, such as computing the area of a rectangular plot, this process is relatively straightforward, since the details of the solution are well understood. In other cases, such as computing the orbit of a spacecraft or predicting weather patterns, the programming process can become quite complex and time-consuming. Even after an algorithm has been developed and converted into a computer program, the programmer must still make sure that the program is correct and will function as desired in all situations. The actual process of writing statements in BASIC or some other language often represents only a small portion of the time spent on a programming project. The program development process involves the following five major steps in sequential order: problem analysis, algorithm development, coding, testing, and documentation. In the following sections we will describe the purpose of each of these activities and techniques of program development. 2.2 PROBLEM ANALYSIS

The first step in solving a problem on a computer is problem analysis which requrtes that we study and understand fue given problem. If the problem is physical and not mathematically /logically formulated, then it is converted into a mathematical/logical model precisely. Then we identify the information required tc: be computed and printed (output) and that available (input) to the computer. Once the input and output data are identified, we ascertain whether all the input items necessary to compute the required output are available; if not, then, before proceeding further, additional information needed is determined and provided. 19

20

COMPUTING WITH BASIC

2.3 ALGORITHM DEVEVELOPMENT The most fundamental concept in computing is that of algorithm. The word 'algorithm' originates from the word 'algorism' (that is, the art of computing with arabic numerals) which stems from the name of a famous Arab mathematician Abu Zafar Muhammad lbn Musa Al-Khwarizmi (825 A.D.) who first suggested the mechanical method of adding decimal numbers by taking one digit from each of the operands and the previous carry digit (if it exists). An algorithm is a sequence of instructions/ steps that are necessary to be executed to produce the solution to any problem of a given type. The steps may be : (a) input, (b) assignemnt, (c) decision, (d) repetition (or iteration), and (e) output. An algorithm may have the following properties, namely, definiteness, finiteness, nonintuitiveness, generality, and input/output. Definiteness: The steps of an algorithm should be unambiguious and precise. Finiteness: An algorithm terminates after a finite number of steps. Nonlntuitiveness: Algorithmic instructions/steps are nonintuitive (that is, apprehended with reasoning or analysis) and are executed mechanically. Completeness/generality: An algorithm is general so that it can solve any problem of a particular type (for any input data) for which it is constructed. Input/Output: An algorithm is like a machir.e; it has precise inputs (initial data) and outputs generated in the intermediate steps and in the final step of the algorithm. If any algorithm is not known for a problem, a procedure known as "heuristic"• can be sometimes improvised to get some guess or intuition about finding a solution to the problem or feel of the problem. It may be noted that an algorithm is a rule (proved steps} to solve a problem but a heuristic is only a guide towards finding a solution. Although a heuristic may not lead to a solution of the problem, it may still give an idea of improving it for a better performance next time. We give a few illustrative examples in which the problem is first stated and then the algorithm is written. Example 2.1: Find the larger of the two unequal numbers x1 and x2. 1. Get the values of x1 and X2 2. If x1 > X2 then set greater = x1 else set greater = X2 end of comparison 3. Print greater 4. Stop. Example 2.2: Find the largest of the three distinct numbers x1, x2, and X3. 1. Get the values of x1, X2. X3 2. If x1 > X2 then if x1 > X3 then set greatest= x1 else set greatest = X3

*

If a problem is terribly ill-defined or too long (for example, chess problem), no "Tlathematical technique by itself can solve it. The computerisation of the solution requires all the vauge, hard-to-quantify ideas that humans in fact make use of for solving this problem. The collection of these rules, sometimes referred to as an insight, intuition, or experience with a particular task, represent what computer scientists call 'heuris~cs'.

PROBLEM-SOLVING ON A COMPUIER

21

end of comparison else if X2 > X3 then set greatest = X2 else set greatest = X3 end of comparison end of comparison 3. Print greatest 4. Stop. Ezample 2.3: Find thelargest number in a list of n distinct numbers, x1. X2 , ... , xn . 1. Get the value of n (~ 2) and those of x1, X2 .... , Xn 2. Setj = 2 3. Set greatest =x1 4. While j s n do if greatest < XJ then replace greatest by XJ increase j by 1 else increase j by 1 end of comparison end of loop (repetition) 5. Print greatest 6. Stop. Ezample 2.4: Consider five sets, each of ten positive real numbers. Also. consider the largest number of each set. Find the largest of these five numbers. 1. Seti= 1 2. Set greatest = 0 3. While i s 5 do get the numbers X1J ( j = 1, 2, ... , 10) of the ith set sety1 = xn setj = 2 while j :S 10 do if y1 < x1J then replace Yt by XIJ increase j by l' else increase j by 1 end of comparison if greatest < y1 then replace greatest by y1 increase i by 1 else increase i by 1 end of comparison (selection) end of loop (repetition)

22

COMPUI!NG WITH BASIC

end of loop (repetition) 4. Print greatest 5. Stop. Note: If the foregoing real numbers are not all positive, then choose greatest = a number less than all the given fifty numbers. 2.4 FLOWCHART DESCRIPTION OF ALGORITHMS

For the man-man communication of the steps of an algorithm, the flowr.hart language is an excellent vehicle. :Although a natural language, say English, along with the conventional mathematical notation can be used to describe (represent) an algorithm, 'there are several drawbacks: (i) A natural language is ambiguous and imprecise and does not permit the description to be concise. (ii) The basic structure of the algorithm is not revealed. A flowchart is a graphical representation of a specified sequence of steps of an algorithm. It is a diagram of characteristically shaped boxes connected by directed line segments. Each box represents a group of elementary steps of an algorithm. Each directed line shows the flow of the algorithms. Bozes: The elementary boxes can be divided into seven types. They are: (1) Assignment/function/assertion boz: This is a rectangle (Fig.2.1) and operations contained in it. are executed when the box is entered. The entry to the box is one and the exit is also one. The symbols "=" or ":=" or "+-" within the box indicates that the content (or the value) of the location c is replaced by the result of the addition of the contents of the locations a and b. Set c =a+ b [ Compute c+d-e

or equlivalently or equivalently

c:

=a+b

or equivalently

c +- a+b

I compute r cc. d. e) = c+d-e

Fig. 2.1 : Assignment box

(ii) Text/decision boz: This is usually a diamond (Fig. 2.2) and indicates a conditional transfer in an algorithm. A condition is tested and alternative actions are taken based on the outcome of the test.

l False

,..__ _ _ Conditional branches

Conditional branches

Fig. 2.2 : Decision box.

(111) Input/output boz: This is usually a parallelogram (Fig. 2.3) and indicates the input or output of information to or from the computer. The exact operation (input or output ) to be performed is specified inside the box.

23

PROBLEM-SOLVING ON A COMPUTER

...... / __Re_ad_li_st_ __,/

j______ Input list

,

J

Read a, b, c

~-/

j

_,

j

Fig. 2.3 Input/output box

(iv) ModUler boz: This is a pentagon (Fig. 2.4) used when a modification or change in the steps has to be made. It l.s to be noted that such a modification in an algorithmic step is not desirable. (v) Group instruction boz: This is a hexagon (Fig.2.5) that indicates a group of steps (instructions) or a subalgortthm.

Fig. 2.4. Modifier box

Fig. 2.5. Group instruction box

(vi) Connection boz: This is a circle (Fig.2.6) used when it is inconvenient or impossible to directly join some two boxes in a flowchart.

&-!

True

False

Fig. 2.6 Connection box

(vii) Start/stop boz: This is flat-oval (Fig. 2.7) used to indicate the start/entry or stop/exit point in a flowchart.

( Fig. 2.7 Start/stop box

24

COMPUI'ING WI1H BASIC

To illustrarte this step of problem-solving process, the flowcharts of Examples 2.1, 2.2, 2.3, and 2.4 are given in Figs. 2.8, 2.9, 2.10, and 2.11, respectively.

False

True

Greater=

Greater= x2

x1

Print Greater

(

Stop

)

Fig. 2.8 : Flowchart for Example 2.1

Start

Input x1. x2, x3

Stop

Fig. ?.9 Flowchart for Example 2.2

25

PROBI.EM-SOLVING ON A COMPUTER

S1art

Input Xt. x2,

... ,.Jlo

False

False

j Print Greatest

/

~ j=j+l

Fig. 2.10 : Flowchart for Example 2.3

2.5 TOP-DOWN PROGRAM DESIGN A complicated problem becomes difficult to analyse, and the corresponding program steps become numerous so that their interrelationships are difficult to keep in mind all at once. One approach to the management of complexity, when it is overwhelming, is the top down program design based on the divide-and-conquer strategy. When using a computer to solve a problem, you should start by understanding the problem thoroughly. You start at the "top" by figttring out what your program is supposed to do. Next you split your prospective. program into a few modules each of which performs a distinct function. Because these main functional modules contain the higher-level co.ntrol logic/function and are most critical to the success of the program, they are designed first. Then the next lower-level modules for each higher-level module are created in the same manner. In this way, most of the details of the solution plan are left until the lowest level modules are designed. Thus, a program developed by using a top-down design consists of modules created and related in a treelike (hierarchical) structure. The flow of control is from the highest-level module/algorithm (the origianl problem) to the lowest-level modules (the machine language program). Each module is called, or invoked by a next higher level module. Note that there exists no precise definition of (the size oO a module so that one can automatically /mechanically form a module. When you are writing a program, you should start with an overall understanding of the program's purpose. Then you formulate the solution in terms of generalised statements. This first version of the algorithm is typically limited to expressing the general logic of the solution, not the details of any particular computation or any specific action. Once the general algorithm has been developed, it can be refined by adding the details that are necessary to perform the general actions. For a complicated problem, this refinement process may be repeated several times with each version

26

COMPUIYNG Wl1H BASIC

Start

False

False

True

Greatest = y;

j=j+l

Stop

Fig. 2.11 : Flowchart for Example 2.4

containing more details than the last. In other words, you _should proceed step by step towards the writing of this program. The last step refines the method to the level where the computer can carry out the specified operations. This means that the final refinement results in a program which can be executed by the computer. As you can see, the idea behind top-down programming is step-by-step reji.nement leading from the problem statement (algorithm at the highest level ) to the final program (algorithm written in a programming language).

PROBLEM-SOLVING ON A COMPUI'ER

27

2.6 STRUCTURED DESIGN APPROACH Earlier Uate fifties and early sixties) there were few formal techniques or guidelines for developing algorithms. In response to the chaotic situation caused by a multitude of individual styles and methods, a new programming discipline known as structured programming emerged. During the past several years, structured programming has been introduced and successfully applied to program development. Originally perceived as the panacea for virtually all software-related difficulties, it has proven to be extremely beneficial to software development when properly applied. Proponents of structured design concepts believe that the application of these concepts will result in logically sound, well-thought-out program solutions. The structured approach leads itself to the development of programs in which a hierarchy of program moldules provides the basis. of the solution. Essentially, a structure similar to an organisation chart is constructed, with modules at each level that define specific processing activities. This approach is very helpful when it is applied to the design of large program solutions, where many complex components must be integrated throughout all levels of that design. Though BASIC is not a fully structured language, it lends itself to the application of many structured concepts. It is important that the beginners master these concepts, as they are incorporated into many currently popular languages. Structured concepts also provide a means of self-discipline and greatly assist in the preparation of programs that are logical and easy to debug. The basic steps in top-down structured design are: 1. Brt: tk down the problem into a modular structure such that each module of activity has only one input (entry) and 0nly one output (exit). 2. Minimise/eliminate the 1;1se of unconditional branching (GOTO) statements. 3. Establish a hierarchical (top-down) structure for program modules. Structured design eliminates solutions that are a hodgepodge of elements, that is, it eliminates unintegrated, illogical bottom-up solution. By examining a problem from the top down and dividing it into modules, the programmer is forced to integrate eacp module logically into the overall design. Thus, a logical flow of information will result. In other words, one should strUcture (organise) his program in a top-down or layered fashion so that the program can be reviewed as a collection of distinct interrelated modules, each module being simple and clear as to its purpose or task; there is no widely accepted precise definition of the size of a module. The application of structured-design principles to software development is called structured programming. Structured programming is an approach to programming that (1) facilitates program developemnt, (2) improves program clarity - the ease with which a person unfamiliar with the program, including possibly the original programmer, can read the code and determine what is occurring, and (3) simplifies program debugging. When structured programming principles are properly applied, well-conceived software results. Three advantages associated with structured programming are: • Sound solutions whose logic is readily followed. • Reduced testing and debugging time. • Improved programmer output. The impact of structured-programming efforts is best measured in larger, more complex programs, where logical relationships must be clearly defined. Large programs adopting these principles are more readily maintained and easier to modify when upgrading is necessary. A structured program is written using only three basic control structures, or construction blocks; sequence, selection, and repetition. Such a program can be represented as a structured (or well-formed) flowchart (with one entry and one exit) consisting of only these three basic construction blocks. Each o( these structures/blocks has a single entry and a single exit. The program listing is easy to read because there is no random branching (forward or backward) from one part of the program to another part. Since control flows from the top to the bottom, the listing can be read more or less Hke a book. The program logic is easy to follow.

28

COMPUIYNG WITH BASIC

2.6.1 Sequence Structure The sequence structure indicates the sequential flow of program logic. In other words, it recognises the fact that program instructions are generally executed in the order in which they are stored in the computer. Thus, in Fig.2, 12, the instructions in the sequence are performed one after another, that is, instruction 1 is performed before instruction 2 and control simply flows from instruction I to instruction 2. None of these instructions results in a branch to another part of the program. This is a good programming practice. Branching to another part of the program should be avoided. One of the objectives of structured programming is to eliminate/minimise branches of a sequence structure. When there are branches, it is more difficult for the programmer to follow the program logic. Therefore, program debugging and maintenance are harder. The sequence structure is represented by such statements as LET, READ, INPUT, PRINT. It may be noted that each block may stand for a statement; it may stand for a whole module, or even a collection of modules.

1 instruction 1

instruction 2

instruction n

Fig. 2.12 : Sequence structure

2.6.2 Selection Structure The selection structure (also known as decision structure) indicates conditional program flow. It consists of a test condition and one or more blocks of instructions. The outcome of the test determines which of these blocks is to be executed. A selection structure is often called an IF /THEN,

IF/TiiEN/ELSE, or Case structure, depending upon whether there are one, two, or many blocks of instructions from which to choose. (As we shall see in Chapter 6, other names for these are, respectively, single-, dual-, and multiple-alternative decision structures.) These decision structures are shown in Fig.2.13. As shown in Fig.2.13(a), if the test condition is true, then sequence 1 of instructions (also known as THEN block of instructions) is executed; if it is false, sect~•,.nce 2 of instructions (also known as ELSE block of instructions) is executed. The IF /THEN si... "'ture (Fig.2.13(b)), also known as missing ELSE structure, is a special case ofIF /THEN /ELSE structure..:' the test condition is true, the instruction sequence is done; if false, nothing is done. Section 6.6 shows how the IF/THEN, IF/THEN/ELSE, and Case structures are implemented in BASIC. In situations where our programs must ~ontain more than two alternatives, we use a case structure. As shown in Fig. 2.13(c), one of the alternatives is chosen based on the integer value (rounded if necessary) of the numeric expression e (the test condition). A true Case structure, containing just one test condition, can only be implemented by an ON GOTO statement (see Section 6.2). However, it can be imitated by chaining IF /THEN structures (see Fig. 2.15(a) and Fig.6.3). In Microsoft or VAX-11 BASIC, simple IF/THEN/ELSE structures can be coded using an IF/THEN/ELSE statement.

2.6.3 Repetition Structure The repetition structure (also known as loop structure) provides for a looping operation, that is, repetitive execution of a program segment. There are two fundamental types : DO /WHILE (pretest) and DO/UNTIL (posttest) loops.· DO/UNTIL loops are also known as REPEAT/UNTIL loops. DO/WHILE loops are also known as WHILE/DO loops. These two loops are shown in Fig.2 14. The flow of control in the DO/WHILE loop can be described as "do the instruction sequence instruction 1, instruction 2, ... ,instruction n while the test condition is true". When the condition is false, the instruction sequence is skipped and the flow of control continues in the program sequence. It may be noted that the condition for a DO/WHILE loop is tested before the statements

29

PROBI.EM-SOLVING ON A COMPUTER

for the loop are executed. The loop may not be executed even once if the condition is false when it is first tested. The FOR/NEXT statement (described in Section 6.4) is a special type of pretest structure.

True

True

False

False

Instruction sequence

(b) IFffHEN structure

(a) IFffHEN/ELSE structure Enter

(c) Case structure Fig. 2.13 : Selection structure - different forms

The DO /UNTIL loop is similar to the DO /WHILE loop, but the condition is tested after the statements in the loop are executed. An important difference between the DO /WHILE and DO /UNTIL loops is that the DO/UNTIL loop is always executed at least once, whereas DO/WHILE loop might not be executed at all.

Instruction I

Instruction n Instruction 1

Instruction n

(al DO/WHILE Loop

(bl DO/UNTIL Loop

Fig. 2.14 : Repetition structure

30

COMPUI1NG WITH BASIC

As shown in Chapter 6, these loops can be implemented in all versions of BASIC by using FOR/NEXT statement or combinations ofIF /THEN and GOTO statements. In many modem versions of BASIC, other construtions such as Microsoft's WHILE/WEND are possible. One of the objectives in using the three basic structures is to make programs more understandable to those concerned with design, review, and maintenance. It is possible to combine the three simple structures to produce more complex coding while maintaining the simplicity inherent in each of the three structures. For example, the programming logic may involve a selection between two program paths. If one path is chosen, there should be a repetition loop; if the other path is

sign for less than

@

comma

sign for greater than

colon percent exclamation mark

opening parenthesis equals sign

number sign semicolon

ampersand

at sign

question mark back slash underscore decimal point

The typewriter keyboard of the terminal which is used to type in a program has many more characters, some of which are needed to communicate with the computer and to do special jobs. For the purpose of writing programs in BASIC, however, only those characters given in the character set must be used. It is extremely important to note the distinction between similar characters, such as the digit 0 (zero) and the letter 0 (oh). the digit l(one) and the letter I. the digit 2 (two) and the letter Z (zed), or the digit 5 (five) and the letter S (es). Remark: The small letter b superimposed by a slash (la) is used to indicate blank space. A delimiter is an item oflexical information whose form and/or position in a program denotes the boundary between adjacent syntactic components of the program. As is true with any natural language, the meaning and clarity of statements in BASIC often depend on the inclusion of explicit indicators that punctuate the statement. In the latter context, such symbols are termed delimiters. The blank space. the comma. the semicolon. and the parentheses are used as delimiters whose functions are self-explanatory. 3.2 INTRODUCTION TO TIMESHARING BASIC was Q.esigned for, and is particularly well suited to, a timesharing mode of operation. In this mode, the computer can be accessed from numerous on-line devices called terminals (each terminal having a keyboard and a display unit, which are the parts we are most concerned about): its internal memory has space allocated for each of the terminal users. and it switches its attention sequentially among the terminals being used. The term "on-line" refers to a device that becomes connected to and under the control of the computer that will actually do the processing. The terminals are connected to the computer either via direct wiring (hard-wired) or over telephone lines or a microwave circuit. Thus. a timesharing terminal can be located remotely - perhaps several hundred kilometers away from its host compu~er. Since a computer operates much faster than a human sitting at a terminal, one computer can support a large number of terminals at essentially the same time. In other words. input/output on the terminals is usually a very slow operation relative to the time required for calculations. This is why an individual user may not even be aware that he does not enjoy the undivided attention of the computer. unless the system is very heavily loaded, although the computer will, in general, only devote a small fraction of its time (on a DEC 10 system 1/50 of a second at a time) to a terminal. For the rest of the time that job is suspended : the program, its data, and information about where it was suspended are held on a secondary storage so that it can be restarted at the right place when its tum for active processing comes round again.

GETITNG STAR'IED IN BASIC : GENERAL INTRODUCTION

45

Timeshartng is controlled by a set of supervisory programs collectively known as a rrwnitor, with which the user interacts by issuing monitor commands. The monitor controls the sharing of resources among jobs, and is active whenever the computer is running. The monitor is the main component of the operating system of the computer. Timeshartng is interactive or conversational - the user submits a program and its data to the computer through the keyboard of a terminal. The computer executes the program and then either prints results onto large sheets of paper or displays them on the 'IV /Video screen immediately. (Printed output may be more desirable for some types of applications, since it provides a "hard copy" of the interactive session; however, the use of a 'IV/Video display is uswally more convenient.) The significant feature of interactive computing is that the user and the computer are able to converse with each other during the computational session. Thus, the computer may periodically pause to ask the user to provide certain information that will determine what subsequent actions are to be taken by the computer and then hurries on as soon as the user has finished typing his message. The timeshartng system is in contrast to a batch processing system where a number of jobs is read ill to the computer and processed sequentially. (A job refers to a program with its associated data that are to be processed.) Usually the program and the data are recorded on punched cards or a (floppy) diskette; thus there will be usually a different deck of punched cards or a diskette for each job. The information recorded on the cards/diskette will be read into the computer by means of a mechanical card reader /floppy rea~er. After the job is processed, the output, along with a listing of the computer program. will be printed c.n large sheets of paper by a high-speed printer. In a batch processing system, users may not get their results from the computer centre for several hours/ days. In addition to obtaining a quick response, timeshartng users enjoy another major benefit. A person finds out quickly whether a program is working properly. If it is not, the user can change the program on the spot and try it again while everything is still fresh in his mind. This should result in less overall time required to write a program and allow testing it enough to clear up all errors. Certain features of batch processing and timesharing can be combined if desired. For example, it is possible to enter a set of input data directly from a terminal (thus eliminating the need for key punching or keying in information onto a diskette) and then proceed to process the data in the batch mode. Another possibility is to use a card reader or a floppy reader (batch processing) to enter a program and a set of data, and then edit (modify) the program and process the data in the timesharing mode. Such "hybrid" operations are becoming increasingly common as computer systems grow in sophistication. Card punching and reading that had dominated the data processing scene up to about 1980 are now globally almost nonexistent; however, their mention here has historical importance. The BASIC language was designed to be conversational right from the start. This can put the programmer or user into direct communication with the computer, usually through a teletype terminal. In this interactive mode, the user can enter his program statements directly into the computer memory and any errors in the statements will be immediately displayed. Thus, the user can correct his mistakes immediately. While running the program, the programmer can ask for the results at intermediate points and check for the correctness of his program logic without having, for the computer, to reach the end of the program. BASIC, like any other language, can be run in batch mode as well and the majority of computing is still done in batches.

3.2.1 The Keyboard For the BASIC user, the terminal is the chief means of communication with the computer. The user will have to familiarise himself with its keyboard. A typical keyboard layout is shown in Fig. 3.1. There are other arrangements, but this is the most common. The letters and numbers are where they would be on an ordinary typewriter; but there are a few symbols which are not usually present on a typewriter, such as:


A

\.

There are also some special keys. The most important of these are : Return which causes carriage-return and is used to terminate an input line; Rub-out which erases the last character typed in; and CTRL which is used to produce the 'control' characters. The control characters have

COMPl.nlNG W11H BASIC

46

special effects and are obtained by holding down the CTRL key while typing the character concerned. For instance,'control-C, which is represented in this text as CTRL/C and which causes a circumflex C to be printed ("Cl. is obtained by typing C while pressing CTRL at the same time.

.,

n

f3

f4

P1

,, " fl

""

Pl4

Fig. 3.1 Typical keyboard layout

CTRL/C halts a running BASIC program when it is waiting for input; CTRL/O suppresses whatever is being printed by the computer; CTRL/U deletes an entire line of input, and so on. These special characters can be used from within the BASIC system. It is essential for the beginner to get used to the keyboard, and the main requirement for this is practice. There is no need to be a star typist, but on the other hand if it takes you several seconds to hunt for every character then you will not find your terminal sessions very enjoyable, or productive. The user should notice particularly that the number 1 (one) is different from the letter 1 (el) and that the number O (zero) is different from the letter 0 (oh). The computer is very fussy about these distinctions; if the user types one when he means the other, it will cause problems.

3.3 RUNNING A BASIC PROGRAM We have learnt in Sections 1.3.2, 2.10, and 2.11, how a program is executed. We have known that a programmer communicates with a computer through a terminal. We also have learnt how to write BASIC programs. In this section, our attention will be directed toward the use of "hardcopy" terminals within a timesharing environment. In other words, we shall see how these programs can be entered into the computer, edited, saved, and executed. We shall also consider some methods for detecting and correcting various types of errors that can occur in improperly written programs. Two types of statements are required to use the BASIC language. One type of statements is referred to as program statements that instruct the computer in details as to both the specific operations to perform and the order in which to perform them. This type of statements is the subject of this text. Second type of statements is known as operating system and editing commands. These commands, in contrast to program statements, instruct the computer as to what action to take concerning the program itself. The nature and extent of operating system and editing commands vary. The commands described in this chapter apply specifically to the DEC 10 system. However, the commands required to use (i) Digital Equipment Corporation (DEC), (ii) Hewlett-Packard (HP), and (iii) International Business Machines (IBM) computer systems are sumnarised in Table 3.1.

3.3.1 Logging In The first step to communicating with a computer through a timesharing terminal is to establish a connection to the computer. For this, the user will almost certainly have to go through some sort of identification procedure, known as the 'logging in' or the 'logging on' procedure. 'The logging in procedure for the DEC 10 system is briefly described below. There is a striking resemblance between logging in on most timesharing systems but they differ at various points: the user is advised to find

47

GETI'ING STAR'IED IN BASIC : GENERAL INI'RODUCIION

out the details of account codes, passwords, and so forth on the machine which he will be using. He will have to obtain a user-number or user-name if he does not already have one. The logging in procedure begins by ensuring that the terminal is properly connected to the computer, then by switching it on and checking the line. Some terminals have dial-up facilities. The user calls the computer via a special telephone used for data transmission. If the appropriate telephone number is dialed, the computer will answer via a highpitched tone transmitted over the telephone line. This signals that the computer is ready to receive input from the terminal. The user then places the telephone handset into an acoustic coupler. This links the terminal to the computer through the telephone line. The logging in procedure is dependent upon the particular computer system being used. A DEC system signals its readiness by printing a full stop (period) at the left margin, the user then types WGIN (one wcrale is a name given to a quantity (of information) whose value may change during execution of a program. We have said that a computer has a memory and that in the memory there are locations where information can be stored. ~ach location has its own unique

*

In such versions, the maximum size of a string constant is defined by the size of the print zone (see Section 5. ). The string constant must fit easily within the print zone and cannot exceed its maximum size.

57

CONSTANTS, VARIABLES. EXPRESSIONS, AND SI'A'IEMENTS

address. In a high-level language llike BASIC we do not ever refer to an actual machine address. Instead we use a name to identify a particular location. It is like referring to a house by the name of the owner rather than by its address. As far as the computer is concerned, a variable is the name given to a location in its internal (main) memory where the value of the variable is stored. (When a value is assiged to a variable, that value is stored in a memory location identified by the variable ·name. A variable name is also known as identifier.) There are three types of variables in. BASIC : numeric variable, string variable, and subscripted variable. In this section. the numeric and string variables are discussed; subscripted variables will be discussed later.

4.2.1 Numeric Variables A numeric variable name refers to a memory location where the numeric vlaue of one variable is stored. A numeric variable name can be a single letter of the alphabet or a single letter followed by a single digit (0 through 9). Thus, the BASIC programmer has very little freedom in naming variables. Some valid numeric vartable names are shown below : zg A N AO N5 z Following variable names are invalid : X55 (too long) (a name cannot consist of two letters of the alphabet) FX 5X (a name cannot. begin with a digit) A* (a name cannot include a special character except$,%,#,!) The same name with different end characters are interpreted as distinct variables. For example, if X, X1. X2. X3 and X4 all appear in the same program, then they are interpreted as separate, independent variables. The advantage of the short names is to reduce the size and complexity of the BASIC interpreter. In fact, the restrictions in naming the variables has made BASIC a most suitable language for micro and minicomputers. The disadvantage is that short names are difficult to remember. For example, the long name VALUE is more descriptive and memorable than the short name V. To improve Table 4.1 Variable names allowed in BASIC Computer

Characters allowed

Number of characters allowed

Apple II Commodore 64 TRS-80

Letters, digits

Any number of characters but computers recognise only the first two.

IBM PC Macintosh

Letters, digits, periods

Any number of characters bu! computers recognise only the first forty.

VAX-11

Letters, digits underscores

A maximum of twenty-nine characters

readability, most of the modem versions of BASIC permit variable names that are longer than two characters. In fact, some versions of the language do not place any restriction on the maximum permissible number of characters. Although the characters that can be used to name a variable and the number of characters allowed in a variable name vary, depending upon the version of BASIC being used (see Table 4.1 ). in all the versions the first character must be a letter. For example, the following are valid longer variable names : RESULT

SUM

ROOT

STUDENTl

STUDENT2

The following are not valid : A2B2 STIMES FIVE-TIMES

(letters are nonconsecutive) (starts with a digit) (special character not allowed)

STUDENT25

CASE13

58

COMPUI!NG WTIH BASIC

Clearly a program with long, explicit variable names is more readable. In this text, however, we shall use only short names. It is to be noted that long names are simply a matter of convenience and will not affect the program any way. Moreover, the enhanced versions of BASIC generally allow multiple numeric data types and thus integer, real (single-precision), and double-precision constants are represented by integer, (single-precision) real, and double-precision (real) variables, respectively. The different variable types are generally identified by the last character of the variable name. Typically an integer variable ends with a percent sign (%), a single-precision real variable ends with an exclamation sign(!), and a double-precision real variable (or, simply double-precision variable) ends with a number sign (#). (It is to be remembered that a string variable must end with a dollar sign ($).) If a variable name does not end with any special character, it is interpreted as a (single-precision) real variable. Some BASIC variables, and their corresponding types. are given below: ROLL%

Integer

TAX!

Real (single-precision)

NAME$

String

ERROR#

Double-precision

PAY

Real (single-precision)

The variables should be named in such a way that they are clearly indicative of the quantities they represent. In such BASIC versions which allow long variable names, this is easy to do, but even in a BASIC version which allows only short names (or recognises only the first two characters), one can follow this advice. Variable

Poor name

Tax Rate of pay Price of item I Average score

Better name

Short T

A B C D

Long TAX RATE PRICE I AVG

R Pl A

Remark : In some versions of BASIC, numeric variables are preset to zero at the start of program's run. It is unwise, however, to depend on this feature : better practice is to initialise all variables yourself, even if they start at zero.

4.2.2 String Variables Most versions of BASIC permit the use of string variables that bear the same relc... ~.·--11ship to string constants as numeric variables do to numeric constants. A valid numeric variable namt . ·lien terminated with a dollar symbol ($) becomes a valid string variable name. For example, any of the following variable nariles can represent a string : N$

A$

AO$

Z$

NI$

Z9$

Some invalid string variable names are : XI

(No dollar sign)

$Y

(Dollar sign must be the last character)

Z$

(No blanks are allowed)

If the user's BASIC allows long names, here are some more valid string variable names : NAME$

LAST$

MONTH$

DAY$

CITY$

4.3 EXPRESSIONS Expressions in BASIC are formed according to the same rules of algebra as used in Mathematics. Special symbols (called operators) together with parentheses are used to connect (meaningfully) constants, variables, functions, or a combination of one or more constants, variables,

CONSI'ANIS, VARIABLES. EXPRESSIONS. AND SI'A1EMEN1S

59

and functions. BASIC allows three types of expressions : arithmetic expression, relational expression, and logical expression. Thus the operators in BASIC are also classified into three categories : arithmetic operators, relational operators. and logical operators.

4.3.1 Arithmetic Expressions An arithmetic expression may be simply a numeric constant, or a variable. or it may be a combination of constants and variables using arithmetic operators to produce a single value. The arithmetic operators, in order of precedence, are :

Operator

*,/ +,-

Sample Expression

Operation Exponentiation Negation Multiplication, Floatingpoint division Addition, subtraction

A"B -A A*B A/B A+B,A-B

Operators having the same priority are evaluated from left to right. Parentheses are used to change the order in which the operations are performed. Operations·within parentheses are performed first: Inside parentheses, the usual order of operations are maintained. Thus X+Y /3 means first divide Y by 3, then add X to the result; while (X+Y)/3 means add X to Y, then divide their sum by 3. This shows that paired brackets may be used to impose any desired order of evaluation. if the default priorities are not suitable. The picture is somewhat complicated by the fact that the plus and minus signs can assume three distinct roles. The three roles of the minus sign, for instance, are as that of the sign of a number (-7), the negation operator requiring only one operand (-X), and the subtraction operator (7-X). Confusion can be avoided by judicious instrtion of zeros and brackets. It is to be noted that two consecutive operators must be separated by parentheses. The best policy for the beginner is to avoid very long complex expressions, where possible, by breaking them down into simpler steps, and to insert brackets whenever ambiguity might arise - even if not strictly necessary. However, it must be noted that for every left parenthesis in the expression there must be balancing right parenthesis. Here are some algebraic expressions and their BASIC counterparts : Algebric expressions

BASIC Expression

g

X*Y/Z

z x4y-3

X"4*Y"(-3)

be

A"B"C

a

( b2 -4ac )lfi 2cax

2

+bx +c)

(B"2-4*A*C) "0.5 2"(A *X"2+B*X+C) X+(Y/Z)

x+l'.. z

W +X/(Y*Z)

x w+yz z

(w+x)Y

((W+X) "Y) "Z

A(-B)

A* (-B)

Ezample 4.1: Evaluate the expressions: (a) A+ B/C + D/E*F"2 - G and (b) A+ B/(C*X + Y"2) (a) The order of execution can be written as an inverted. tree with operands as nodes, as illustrated in Fig.4.1. It is to be noted that the expressions represent

60

COMPUI'JNG wrIH BASIC

b

d

c

e

,,'l

(a) a + - + - · r -

A + B

I

c

g

(b)

+ D I E • F

A

2 -

A + B I

G

~

a +b- cx+y2 * x + y

A

~

Fig. 4.1 Inverted trees (indicating order of execution)

Exponents in an expression may be either an integer or a real quantity. If the exponent is an integer quantity, the value of the expression is evaluated by repeated multiplication. In other words, 2A4 is equivalent to 2*2*2*2. However, if the exponent is a real quantity, the value of the expression 18 evaluated by multiplying the logarithm of the quantity being exponentiated by the exponent and then computing the antilog. For example, the expression 4A2.3 is evaluated as e2.3log.4

Since the logarithm of a negative number is not defined, it is seen that the operation is invalid if the quantity being exponentiated is negative. Thus the expression (-4)A2.3 is not allowed. Moreover, no attempts should be made to raise zero to negative power; Jor example, in AAB, A should not become zero while B is negative. Modem versions of BASIC include two more arithmetic operators, namely, integer division (\) and integer remainder (MOD). In integer division, each of the two operands ts first rounded to an integer, the division ts carried out, and the qouticnt is then truncated. The integer remainder operation provides the quantity that remains after an integer division has been performed. Some examples of integer division and integer remainder are given below : 19\5 =3 15.7\3.6 = 4 15.2\3.6 =3 15.2\3.3 = 5 19MOD5 = 4 15.7MOD3.6 = 0 15.2MOD3.6 =3 15.2MOD3.3 =0

4.3.2 Relational Ezpreulona Relational expressions are formed by combining two arithmetic expressions with a relational operator. The relational operators are: > greater than >= greater than or equal to < less than = equal to

< >= =Z YZ W"24*X

Result

FALSE TRUE TRUE TRUE

Strings can also be compared alphabetically. In case of strings, the inequality conditions can be interpreted as 'comes before' or 'comes later' rather than 1ess than' or 'greater than'; trailing

CONSfANIS, VARIABLES. EXPRESSIONS, AND SfA'IEMENfS

61

blanks are ignored when comparing strings. Thus "A"

45

?

46

@

47

A

a b

90 97 98

~
6ANDY3 AND NOT(Y=5)) OR Y>Z X=Y OR Y=Z OR Z=X Y>X AND Z>Y AND X>Z

FALSE FALSE TRUE TRUE TRUE FALSE FALSE TRUE TRUE FALSE FALSE

62

COMP1.JT1NG Wl1H BASIC

The hierarchy ofvartous arithmetic, relational, and logical operations in any logical expression, from highest to lowest priority, is as follows : 1. Arithmetic operations are performed first and the order in which the operations are performed is as follows : 1.1 Evaluation of functions (SOR, ABS, LOG, SIN, etc.) 1.2 Exponentiation(") 1.3 Negation (i.e., preceding a variable with a minus sign (-)) 1.4 Multiplication (*) and division (/) 1.5 Integer' division (\) 1.6 Integer remainder (MOD) 1.7 Addition(+) and subtraction(-) 2. Relational operations (=. , . =) are performed next. 3. The logical operators (AND, OR, NOT) are applied last. The hierarchy of logical operators, from highest to the lowest. is as follows : 3.1 Logical Not (NOT) 3.2 Logical And (AND) 3.3 Logical Or (OR) Within a hierarchial group, the operations are carried out from left to right. Ezample 4.2: Evaluate the following logical expressions for X =TRUE. Y = FALSE, I = 3, and J = 5: (a) l+l > J ORJO AND X (b) NOT(I*J > 10 AND X) ORY (a) The given expression is evaluated as ((I+ 1) > J) OR ((J OJ AND X). Arithmetic expressions are performed first.

I

+

1 >

OR

J

I5

""'/ I /

Arithmetic relations are evaluated

AND

10

X

OR

Y

\(/ TRUE

~TRUE I

ALSE

~FALSE Some enhanced versions of BASIC also include the concatenation operator (+) which is used to combine strings. This operator is usually represented by plus sign(+), though an ampersand(&) or a comma may be used in certain versions of the language. 'For example, if X$ = "NET'' and Y$ = "PAY", then the statement

CONSI'ANfS, VARIABLES. EXPRESSIONS, AND SI'ATEMENTS

.63

30 PRINT X$+Y$ will cause the single string NETPAY to be printed. Similarly, the statements 40 LET A$ = "NINE"+"TEEN" 50 PRINT A$ will cause the single string NINETEEN to be printed.

4.4 STATEMENTS An algorithm designed for solving a problem can be easily and precisely described by using a high-level language like BASIC. When the algorithm is coded into the BASIC language, it is called a program which ts composed of a: sequence of BASIC statements. The word 'statement' is used instead of 'instruction' because some of the statements provide information to the computer rather than instructing it to do anything. Thus, a BASIC statement may be classified as executable or non-executable. Executable statements. such as assignment statements, control statements, input/output statements, specify actions whereas non-executable statements, such as remark ·statements, dimension statements, data iniatialisation statements, function defining statements, subprogram statements, declare information rather than demand action. Each BASIC statment is written as a separate line and each line is given a number. (See Section 2.8.1 for details of the arrangement of a BASIC statement). In this chapter only assignment statments are described ; other statements will be described in appropriate sections of the text.

4.4.1 Assignment Statements The variables in a program mus, be assigned to their respective values before they can be used in computations. This can be achieved in BASIC by the following three statements : (i)

LET statement

(ii) INPUT statement (iii) READ/DATA/RESTORE statement

The LET statement is discussed in this section; the other statements will be c;liscussed later. The LET statement is an assignment statement used to assign a value (numerical or string) to a variable. The BASIC verb used in this statement is LET. The general form of the statement is sn LET variable = expression where sn stands for the statement number. The statement number must be an integer between 1 and 9999 (both inclusive) which can be typed/punched anywherem the line/card. The variable on the left-hand side of the equals sign may be one of the three types: numeric variable, string variable, and subscripted variable. The expression on the right may be a constant, a variable, or a combination of constants and variables using arithmetic operators. The expression is evaluated and the resulting value of the expression is assigned to the variable on the left-hand side of the equals sign. The left-hand side can only be a single variable, not an expression. The new value replaces the earlier value, if any. a8sociated with the variable. It should be noted that the symbol"=" does not mean equality in the mathematical sense and thus there is a fundamental difference between the assignment statement and the very similar algebraic equation. The statement 250 LET N = N+l would appear at the first sight to be wrong; however, this implies that the current value of N ts increased by 1. For example, if N was 5 then after the execution of the statement N becomes ,.6. · Words, symbols, numbers, phrases, even entire sentences can be assigned to string variables provided they are given within quotes. Blanks within quotes are st~cant~

64

COMPUI7NG Wl1H BASIC

The following are some examples of valid assignment statements : 100 LETA=B

50LETX=13 150 LET X$ ="CHARLES"

200 LET N$ = "VON NEUMANN"

250 LET Z = (X+ Y)/2

300 LETX=X+l

350 LETD1$ ="MARCH 31"

400 LET 02$ = "1991"

400 LET V:: (4/3)*3.141593*R"3

450 LET A$ = B$

It is to be noted that the variable on the left of the equals sign and the expression on the right must be of the same type (either numeric or string). Thus it is not possible to assign a string constant to a numeric variable and vice-versa. For example, the statement 360 LET A$= (B+C)/2 would be incorrect since A$ ts a string variable and (B+C)/2 ts an arithmetic expression. Some versions of BASIC pennit assignment of the same value to two or more variables by a single assignment statement. For such versions the following assignment statements are acceptable : 15 LET X = Y = 1.2345 25 LET Xl = X2 = X3 = X4 = 0 35 LET X = Y = (B"2 - 4*A*C)/2 45 LET X$ = Y$ = Z$ = "1991" In some modem BASICs, the keyword LET is optional in both types of assignment statements, and in such BASICs, the foregoing examples would be 15X = 13 lOOA= B 150 X$ = "CHARLES" Since, in BASIC, each statement ts written as a separate line, and each line is given a number, it is always advisable to break a lengthy and complicated algebraic equation into several smaller and simpler equations and write the corresponding statements. For example, the algebraic equations

ab ] a +b r = q [ c + d - c2 - d should be represented as t _a+ b 1 - c +·d ab t2=-c2-d y

3 ( ab + ba) -

and

f=

_a 2 3 ('fa + b

~a 2 + 2b2 -~

- (-vab + a)

10 LET Tl = (A+B) I (C+D) 20 LET T2 = (A*B) I (C"2-D)

t2) 113

= q(ti -

113

30 LET Y = O*(Tl -T2) " (1 /3)

and t1 = (ab t2 =

~a

+ ba)3 2

2

+ 2b

10 LET Tl

=(A"B + B"A) "3

20 LET T2 = (A"2 + 2*B"2) " (1 /3)

t3 = f;_2 + -{i;3

30 LETT3 =(A"2)" (1/3) + (B"3) "(1/2)

4='13.b +a

40 LET T4 = (A*B) " (1 /2) +A

f=ti-t2

50 LET F = (Tl - T2) I (T3 - T4) l3-4 Remark: To make a program more readable, its statements should be typed in a consistent manner. Statement numbers containing the same number of digits have a nice visual appeal. For illustration, consider the following two versions of the same program segment :

CONSTANfS, VARIABLES, EXPRESSIONS, AND STATEMENIS

65

Version 2

Version 1

80LETX=1.5

100 LET X = 1.5

90 LETY=2.6

110 LET Y = 2.6

100 LETS=X+Y

120 LETS=X+Y

110 LET A= S/2

130 LET A= S/2

Obviously, Vision 2 has a better readability than that of Version 1. Usually, for short programs (containing fewer than 80 or 90 statements}, three-digit numbers are used; for longer programs, four- or five-digit numbers become necessary. It is also a common practice to choose statement numbers so that each is 10 more than the preceding one. Example 4.3 : Write a program segment that will compute the volume, v, of a pr;amid with a square base, b, 125 feet on each side, and 75 feet in height, h. Use the formula v = b h/3. The following program segment may be written : 100 LETB = 125 110 LETH= 75 120 LETV =((B*B)*H)/3 Ezample 4.4: Robin buys a book on which the book-seller gives 12.5 percent discount; its regular price is Rs.69.00. Write a program segment which computes the net price (after discount) of the book that he has to pay. 10 LET P =69.00 11 LET D = 12.50/ 100 12 LET N =P - P*D

4.5 MIXED-MODE ARITHMETIC It has been seen in Section 4.1 that many enhanced versions of BASIC allow multiple numeric data types. Such versions also allow completely mixed-mode arithmetic involving combination of variables and constants of any type (integer, real, or double-precision), and automatic data conversion. When arithmetic operations are carried out between different types of numeric data, automatic conversions are made whenever necessary for the evaluation of the mixed-mode expression and the result is always expressed at the highest possible level of precision. The following list shows the hierarchy of conversions, from lowest to highest: integer, real (single-precision), and double-precision. Thus, arithmetic operations involving integer and real data produce a real result. Similarly, arithmetic operations involving either integer and double-precision data, or real and double-precision data, produce a double-preciison result. The result of an arithmetic expression may be of the type integer, real, or double-precision, depending on the types of its elements. The expression is evaluated step by step and each step represents an arithmetic operation which yields a result to be used in the next step. The resulting type of each step is determined as showp in Table 4.3. Table 4.3 Resulting type of mixed-mode arithmetic operation with+,-,*, I or" Second operand I R D

First operand

I

I

R

D

I= Integer

R

R

R

D

R=Real

D

D

D

D

D = Double-precision

The numeric assignment statement also results in conversion if the variable on the left differs from the data type of the result on the right. A real number on the right is truncated to integer if an 5

66

COMPUTING WTIH BASIC

integer variable appears on the left (some versions of BASIC round rather than truncate the real number). For illustration, consider the following numeric assignment statements in which Al = 6.5, B! = 2.0, 1% = 5, J% = 3, D# = 0.18D+l : Assignment statement 10 LETN!=A!/B!

Result N! = 3.25

20 LETN% = A!/B!

N%=3

30 LET RATIO= A!/1%

RATIO= 1.3

40 LET RATIO#= 2/J%

RATIO= 0.6666666666666666

50 LET RATIO = 1%\J%

RATIO= 1

60 LET F! = I%\l.6

F! =2.00

70 LET V = 1% + D#/2.5

V =0.572E+l

80 LET V# =I%+ D#/2.5

V#=0.572D+l

90 LET V% = 1% + D#/2.5

V%=5

100 LET M% = I%"2/J%

M%=8

110 LET V! = (2+D#)"A!/1%

V! = 1173.878

ElC&Dlple 4.5: Write a program segment to find the quotient and remainder of the division of 84 by 19. The following program segment may be written : 10 LET A= 84 20 LETB 19 30 LETO =A\B 40 LET R =A- 0*19

=

D

Exercises

D

1. (a) Explain the various types of constants (numbers) used in BASIC. Give three examples for each. (b) What are the rules for writing constants in BASIC? (c) Discuss the differences between a number written in scientific notation and a number written in floating-point form in BASIC. (d) How many significant digits can be included in a number? (e) What are strings? How are they written? What are they used for? (f) How many characters can appear in a string? 2. (a) Explain the various types of variables used in BASIC? Give three examples for each? (b) What are the rules for naming the numeric and string variables in BASIC? (c) How are integer, single-precidion real, and double-precision real variables written in modem versions of BASIC? 3. Which of the following constants are invalid in BASIC and why? (a) 123 (b) -135.79 (c) "GOOD LUCK" (d) 0.0026 (e) +246.7 (f) (-)360 (g) 3.5E-012 (h) 24E-l.5 (i) ''TOTAL MARKS Ul +246 (k} "X" (1) NAME (m) "246.78" (n) 50% (o) MAY 5, 1990 (p) 7 O'CLOCK (q) "BEAU1YI"

67

CONSTANIS, VARIABI.ES, EXPRESSIONS, AND STATEMENTS

4.

Which of the following variables are illegal in BASIC and why? (al X (bl XY (cl Z23 (d) 5B (f) $D (el C$ (g) P$3 (hl Y +3 (il SUM OJ 19 (kl 01$ (ll REM (r) PI (ml Rl (nl T. l (ol I (pl XlO (ql T* 5. Identify the types of the following constants, variables, and expressions Al$ I NO "7+3" 7+3 6. (al What are the arithmetic operators used in BASIC? What is their natural hierarchy? In what order are operations carried out wihtin a hierarchical group? (b) What is an expression in BASIC? What does it represent? How can the natural hierarchy of operations be altered in an expression? (cl Cite a particular problem that can arise in exponentiation operations. State the reason for the problem and describe how it can be avoided. Evaluate the following expressions assuming A= 2, B = 3, C = 5, and D = 7 : 7. (a) -A " B - D * C " A (bl D - C / A * B (c) (D - Cl I A * B (dl (D - C) / (A * B) (el C * D I A * B (f) (C * Dl I (A * Bl (g) D I A" C I A - B "A (hl (-A) "4 - (A" C) "2 (il (D I A) "Cl A- B "A OJ A" B" 2 (kl 3.5 * 2.6/A * C (1) INT (6.8l +SOR (C" B /A) 8.

How are the following expressions written in the BASIC language ? (bl _a_ a+b

(e) ax+y + 2.5

(f)

- b + '1b 2 - 4ac 2a

(g) a+bc

(il vt- ~ 2

Ul

a+b/c/d

(k)

(cl a

w

~

(dl

~ a + b ) ( c - d )2 ( e - f)3

(h)

2( alb 2p- 1 ( C - 3d) q/r

(ll 271"

2 ~

2m1m2 1 (n) l+-x(p) z-1+ (ol m1 +m2 g 3l+Y 2+z 1-x Find the errors, if any, in each of the following BASIC expressions : (a) XY (c) (Al+Cl/-5 (b) A*+ B (dl D20-E (f) K".5 (el (P--Ql I (R+Sl "3 (g) (X+Y) (X-Y) (hl -5/X+-2 (ml ab+ 1 +

9.

be

(al x+Y z

(i)

c ( d - e )2

3"2.5-25E-046

Ul

(4.5 + 2" {15 - (3+7 /2)})

(k)

u V+W

10. (a) What is the purpose of the assisgnment statement? (b) What are the grammatical rules for writing an assi5nment statement ? Can the keyword LET be omitted from .an assignment statement ? Are multiple assignments permitted in a single statement ? (c) Discuss the similarities and differences between an assignment statement and an algebraic equation. 11. Write an assignment statement for each of the following instructions : (al Assign a value 123.45 to the variable X. (bl Assign the value represented by the variable X to the variable Y. (cl Decrease the value of A by 1. (d) Triple the value of B.

68

COMPUI'ING WITH BASIC

(e) Square the value of C. (f) Assign the product of the vlaues of A, B, and C to P. (g) Assign the average of the values of A, B, and C to V. (h) Assign the length of the hypotenuse of a right-angled triangle, whose other two sides have lengths A and B, to H. (i) Assign the area of a right-angled triangle of altitude A and base B (one-half base times altitude) to R. · OJ Add 32 to the product of C and 1.8 and assign the result to F (conversion of centigrade to Fahrenheit). (k) Assign A times (l+B) to Vl. (l) Assign the string KHARAGPUR-2 to the variables P$. (m) P.ssign the string represented by the variable E$ to the variable F$. 12. Find the errors, if any, in each of the following BASIC statements : (a) 150 LETK-X=N-A*B (b) 70 LETV,W=A (b) 210 LET Y = 7+3, 3*5 (d) 30 LET M, N = 4, 7 (e) 40 LETZ=A*B$-C (f) 120 LETR=P/O.O+Q (g) 130 LET 120 =X (h) 50 LET D$ = 365 (i) 10 LET N+l = 10 OJ 250 LET D = C + (-36) "0.5 (k) 250 LET E = (-3.5"2.5)" 3 (1) 90 LET L = (l+J)/(K-K* 1.0) (m) 100 LETZ19=X-Y (n) LETH=l=J 13. Write an assignment statement that corresponds the each of the following algebraic equtions: a 0.5 (a) p = - - - (b) t = c < 1 +~rn x+y xz b (c) r= (e) 14.

(2+n)f g( n + l)

. [ ( 1 + qm ] (d) v = rr B GOTO 330, 360 80 ON 2-2 GOTO 430, 450 90 ON I+J GOTO K, L 100 ON 2.5 GOTO 470, 480. 490

Valid. Valid. Invalid, only arithmetic expression is allowed. Invalid, the value of the expression cannot be zero. Invalid, variables in place of statement numbers are not allowed. Valid; 2.5 is truncated to 2 and the control goes to statement labeled 480. Example 6.1 : Write a program to compute the value of the nth Legendre polynomial Pn (x)

given by p1 (xl = x p2 (x)

=(3x2 -

1)/2

P3 (x)

= (5x3- 3x)/2

P4 (x)

= (35x4

- 30x2

+ 3)/8

for a given n ( = 1 to 4) and an x. The following program may be written. 10 REM PROGRAM TO CALCULATE NTH LEGENDRE POLYNOMIAL 20 INPUTN,X 30 ON N GOTO 40, 60, 80, 100 40 LETP=X 50 GOTO 110 60 LET P = (3*X"2- l)/2 70 GOTO 110 80 LET P = (5*X"3 - 3*X)/2 90 GOTO 110 100 LET P = (35*x"4 - 30*X"2 + 3.0)/8 110 PRINTN,X,P 120 END

89

CONIROL STATEMENTS

Ezample 6.2 : The possible occupation codes used in a survey and their meanings are shown below: Occupation code 1 2 3

Meaning Service Farming Business

Occupation code 4 5

6

Meaning Student Household Others

Write a program that will write out the meaning associated with an occupation code read from a data record. The following program can be used to solve this problem. 10 REM C =CODE AND P$ =OCCUPATION INPUTC 20 ON C GOTO 40, 60, 80, 100. 120, 140 30 LET P$ = "SERVICE" 40 GOTO 150 50 LET P$ ="FARMING" 60 GOTO 150 70 LET P$ = "BUSINESS" 80 GOTO 150 90 LET P$ = "STUDENT" 100 GOTO 150 110 LET P$ ="HOUSEHOLD" 120 GOTO 150 130 LET P$ = "OTHERS" 140 PRINTC, "MEANS", P$ 150 END 160

Ezample 8.3 : Write a program to solve the following : If code = 1, set bonus equal to 100; If code = 2, set bonus equal to 300; If code = 3, set bonus equal to 500; otherwise, set bonus equal to 1000. The following program may be used. 10 REM C =CODE AND B =BONUS LET B = 1000 20 INPUTC 30 ON C GOTO 50, 70, 90, 100 40 LETB= 100 50 GOTO 100 60 LETB=300 70 GOTO 100 80 LETB=500 90 PRINT "CODE=", C, "BONUS=", B 100 END 110 Remark : A disadvantage of the ON GOTO statement is the need to use GOTO statements to return

to the main processing flow. Since structured designs call for the minimal use of GOTOs, the ON GOTO statement is not popular with the top-down programmers.

COMPUTING WITif BASIC

90

6.3 IF /THEN STATEMENT (CONDITIONAL BRANCHING) We have already learned in Section 6.1 that an unconditional branching operation (that is, a transfer of control or 'jump" from one part of a program to another) can be carried out in BASIC by means of the GOTO statement. Another situation that arises frequently is a transfer to one of two different portions of a program, depending on the outcome of a comparison between two quantities. Such an operation, called a conditional branching operation, permits logical decisions to be carried out within the computer. The IF /THEN statement is a decision making statement and it is used to cany out a conditional branching operation. The general form is : st. no. IF condition THEN n (source) (destination) where the condition may be a relational or a logical expression and it must not be enclosed in parentheses. The statement whose number (n) appears on the right in the description may be any other statement of the same program except DATA, DIM, or Format statement. Some systems accept the words "GOTO" in place of 'THEN". If the specified condition is true, then the control is transferred to the indicated statement Oabeled n). If the condition is false, the IF statement has no effect and the control is passed on to the statement immediately following the IF /THEN statement. The execution of the IF /THEN statement can be represented as in Fig. 6.2. -

The following are some valid/invalid examples :

True

False

Execute statement numberedn

Execute statement immediately following the IFffHEN statement

Fig. 6.2 Flowchart for IF!THEN statement

40 IF X+Y IOO THEN 120 ELSE 20 160 IF X>l8 AND Y>21THEN150 ELSE 30 270 IF XF THEN 50 IF ABS(Y-F)O. Return che value of e raised to the power X, that is, ex. Returns the natural logarithm (base e) of X; X>O. Returns the common logarithm (base JO) of X; X >0. Returns the sine of X where X is in radians. [One degree = 7t/180 radians where 1t (pi) equals 3.14159. Hence X = N(3.14159/180) where N is the number of degrees in the angle specified and Xis the equivalent number of radians.] Returns the cosine of X where X is in radians.

TAN(X)

Returns the tangent of X where X is in radians.

ATAN(X)

Returns the arctangent ofX where Xis in radians; the result will be in the range -7t/ 2 < ATAN(X) < 7t/ 2. Returns the cotangent of X where X is in radians. Returns I if X is positive, 0 if X is zero, and - I if X is negative.

EXP(X) LOG(X) LOGIO(X) SIN(X)

COT(X) SGN(X)

Example

Description

ABS(-5.8) = 5.8 FIX(6.7) = 6, FIX(-5.6) = -5 INT( 1.5) = I because the largest integer< l .~ is

1; INT(-1.5) = -2 because the largest integer< -1.S is -- 2. The functions FIX(X) and INT(X) are identical if X ~ 0. When X < 0, they return the same number if Xis an integer, but the value of INT is one Jess than that of FIX otherwise. For example, FIX(-2.6) = -2, but INT(-2.6) = -3. SQR(4) =2 SQR(2.56) = 1.6 EXP(l) = 2.718282 LOG(2.718282) = l LOG10(1000) = 3 SIN(l.0472) = 3/2 Note that 60° = 60x3.14159/180 = 1.0472 radians COS(.5236) = 3/2 Note that 30° = 30x3.14159/180 = .5236 radians TAN(.7854) = l Note that 45° = 4Sx3.14159/180 = .7854 radians ATAN(l) = .7854

COT(90*3.14159/180) = 0 SGN(l.23) = 1 SGN(O) =0 SGN(-5)=-l

Utility functions TAB(X)

Used in the PRINT statement to format output. It causes the printer to move on to position X in the output line.

SPC(X)

Used in the PRINT statement to indicate how many blank spaces should exist between two output fields. X specifies the number of blank spaces.

The statements JOLETX=30 20 PRINT A; TAB(X); B; TAB(SO); C will print A from the first position, B from position 30, and C starting at position SO. The statement 30 PRINT "NAME"; SPC(S); "ROLL" will cause S spaces to appear between NAME and ROLL.

FUNCTIONS AND SUBROUIJNES

Function RND or RND(X)

Description Returns a different random number which is an unpredictable real number, with a value between zero and one, each time the function is referenced. Zero can actually appear as a random number, but one cannot. The argument (X) may be omitted in some systems. The numbers returned by the RND function are produced by means of a mathematical algorithm known as random number generator. Given a starting number, called the seed, this algorithm ge11erates a sequence of numbers which are random in the sense that any number greater than or equal to 0 and less than 1 is equally likely to occur. However, since the numbers are generated by an algorithm, they are not really unpredictable. (Such numbers are often called pseudo random numbers) Nevertheless.for all practical purposes, the numbers generated by RND are as useful as those that are truly random. Whenever a program containing the RND function is executed, the computer (unless instructed otherwise) always uses the same seed.This means that (except on Apple II and Commodore 64) the same sequence of random numbers will be generated each time the program is executed. This reproducibility of a random number sequence is very helpful for testing and debugging a program. On the other hand, once a program is functioning correctly, it is often desirable to generate a different sequence of random numbers each time the (debugged) program is executed. This can be accomplished by means of the RANDOMIZE statement.The general form of the RANDOMIZE statement is

149

Example The program 10 REM ... RND WITHOUT ARGUMENT 20 DIM A(l 00) 30FOR I= ITO 100 40 LET A(I) = RND 50NEXTI 60 MAT PRINT A 70END causes 100 random numbers to be generated and printed. If the foregoing program does not run, or if the same numbers are obtained in several runs, the following program should be run. The terminal user should enter various integer numbers for X. 10 REM .. RND WITH ARGUMENT 15 DIM A(lOO) 20 PRINT "ENTER AN INTEGER FOR X" 30INPUTX 40 FOR I= 1 TO 100 50 LET A(I) = RND(X) 60NEXTI 65 MAT PRINT A 70END The program 10 DIM X(lOO) 20 RANDOMIZE 30FORI= 1TO100 40 LET X(I) = RND 50NEXTI 60 MAT PRINT X 70END will print a sequence of 100 random numbers. However, unlike the foregoing program.a different sequence of random numbers will be printed each time the program is executed.

st. no. RANDOMIZE Its purpose is to provide a different starting point for the random number generator. Therefore, the RANDOMIZE statement must precede the first reference to the RND function in a program. In some versions (like Microsoft BASIC), its form is

The statement 20 RANDOMIZE 200 sets the seed equal to 200.

st. no. RANDOMIZE e and this seeds the random number generator with the value of the numeric expression e. Record-keeping functions Function Description TIM

Returns the elapsed time (in seconds) since program began. This execution time may also be assigned to a numeric variable. The execution time printed out by the TIM function will always be less than or equal to the total elapsed execution time printed out at the end of the program,

Example The statement 10 PRINT "EXECUTION TIME IS ="; TIM is identical in output to lOLETX=TIM 20 PRINT "EXECUTION TIME ="; X The following program illustrates how the

COMPUI'ING Wf1H BASIC

150

because the latter also includes compilation, execution, and termination time.

three functions may be used in a program. 10 REM ..TYPE IN 20 REM ..TEMPERATURE AND 30 REM .. HUMIDITY RECORDED

CLK$

Provides the time of day. It may be assigned to a string variable, in the same way as the TIM function.

DAT$

Provides the calender date; this may be assigned to a string variable. Tne CLK$ and DAT$ functions are quite useful, especially in the periodic updating of files, such as in inventory control and related systems. Whenever a file is revised by a timesharing system, the date and time of day can be part of the output generated.

40 REM .. ON THE DAY THE 50 REM .. PROGRAM IS RUN. 60INPUT T,H 70 LETT$ = CLK$ 80 LET D$ =DAT$ 90 PRINT "TEMPERATURE IS";T; 95 PRINT "AT";T$; "ON";D$ 110 PRINT "HUMIDITY IS";H; 120 PRINT "PERCENT AT";T$; 130 PRINT "ON"; D$ 140 PRINT TIM 150END

DET

Returns the determinant of a matrix after inversion by MAT INV. This function returns a single numerical value, and does not require an argument. It can only be referenced after a MAT INV statement. If the determinant is zero for a given matrix, then the inverse determined by the preceding MAT INV statement is wrong.

The following program prints the inverse of a matrix X and the determinant of the matrix. 10 DIM X(2,2), Y(2,2) 20MATREADX 30 DATA 1,2,3,4 40 MAT Y = INV(X) 50 MAT PRINTY 60PRINTDET 70END

NUM

Rdurns the number of values entered (from the console) using the last MAT INPUT statement. Whenever the NUM function is referenced, it returns the number of values entered i'1 the most recent MAT INPUT statement.

The program 10 DIM X(200) 20 MAT INPUT X 30 LET X(O) = NUM 40 PRINT X(O) 50END causes an unspecified number of values to be entered and assigned to the elements of X, the number of values to be determined and assigned to X(O), and finally the effective size of the vector X to be printed.

Matrix functions

Random-access file functions LOC(C)

Indicates the current position (storage location) of the pointer for data channel C where C specifies a channel number 1 to 9 with a randomaccess datafile open on it.

LOF(C)

Indicates the last storage location (or the length) of the file on Channel C. These functions are available on G.E. time-sharing systems They may have ot.her names or be unavailable on other systems.

The statement 10 IF LOCO) > LOF(l) THEN 250 causes a transfer of control to statement labeled 250 ifthe pointer for data channel 1 is positioned at any location beyond the end of the file.

String functions ASC(character)

Gives the numeric ASCII code for its argument which is a single character (not in quotes). This number is treated like any other numeric constant

The program 10 LET A = ASC(Z) 20 LET N =2*ASC(F)-A

151

FUNCTIONS AND SUBROUI!NES

Function

CHR$(N)

Example

Description and can participate in arithmetic or any other operations in which numeric constants are entitled to be involved. The list of ASCII codes is given in Table 4.2.

30FORI= 1 TON PRINT ASC( ) + I 50NEXTI 60END is equivalent to lOLET A=90 20 LET N = 2*70 - 90 30FORI=lT050 40 PRINT 32+I; 50NEXTI 60END which will print the numbers 33, 34, ... , 82

This does the opposite of the the ASC function. This gives the character for which N is the ASCII code number. The argument may be an ASCII code or a numeric variable or expression which when evaluated results in an ASCII code.

The program 10LETX=20 20 LET A$ = CHR$(70) 30 LET 8$ = CHR$(4*X+ 10) 40 PRINT A$, CHR$(80), 8$ 50END is equivalent to 10LETX=20 20 LET A$ = "F" 30 LET 8$ = "Z" 40 PRINT "F', "P", "Z" 50END and will cause the letters F, P, and Z to be printed.

40

INSTR (Stringl, This function searchs for String 2 within String l String2) and returns the position in Stringl where String2 starts, if found; otherwise zero. The returned value is an integer which can participate in any arithmetic operations.

The function 10 INSTR("HUMAN","MAN") returns the value 3.

INSTR(N, Stringl, This form of the INSTR function searches String2) Stringl for String 2 and the search begins from the Nth character of String.I. (N is integerised if it is fractional). If String2 occurs more than once in Stringl, then the function returns the position of the occurrence which is first located.

The statements lOINSTR("KHARAGPUR","A") 20INSTR(4,"KHARAGPUR", "A") 30INSTR(6,"KHARAGPUR", "A") will return the values 3, 5, and 0, respectively.

LEFI'$(String,N)

Returns the:: first N characters in the string. A blank is also counted as a character. The first argument of the function must be a string variable or a string constant. The second argument may be a numeric constant or variable or expression. In case it is an expression, it is integerised.

The program segment 10 LET A$= "WEST DINAZPUR" 20 LET 8$= LEFT$ ("BENGALGRAM" ,6) 30 PRINT LEFI'$(A$,4); 8$ will print WEST BENGAL

RIGHT$ (String,N)

Returns the last N characters of the string. Its rules are similar to the foregoing rules of the LEFI'$ function.

The statements 10 LET A$= "NEW DELHI" 20 LET 8$ = RIGHT$(A$,5) 30 PRINT RIGHT$("GOLD" 3), 8$ will print OLD DELHI

152

COMPUTING W1'1H BASIC

Function

Description

Example

MID$(String,l,N) Returns the substring starting at position I in the string and containing N characters. If N is omitted, it returns the substring from I to the end of the string. The first argument of the function must be a string variable or a string constant; the second and the third arguments must be numeric constants or variables or expressions. In case they are expressions, they are integerised by the computer.

The statements IO LET A$= "IMPORTANT" 20 B$ = MID$(A$,3,4) 30 C$=RIGHT$("CAPACITY", 4) 40 PRINT B$; C$ will print PORTCITY

LEN(String)

Returns the number of characters in the strings.

The statements IO A$= "COMPUTER" 20 B = LEN(A$) 30 C = LEN('TAMILNADU") 40PRINTB,C will print the numbers 8 and 9.

SPACE$(N)

Returns N consecutive spaces. N can be a numeric constant or variable or expression. If it is an expression, then it is integerised. It must not be zero or negative. It must not also exceed the number of columns in a line in the display device or printer.

The statement IO LET A$= SPACE$(5) will assign a string ·~· of five blanks to A$. The effect of the statements 20 LET X$ = "JUNE" 30LETY=20 40 PRINT X$; SPACE$(4); Y is left to the reader for verification.

STR$(X)

Returns a string representation of the numeric value X, that is. it converts a numeric constant into string constant.

The statements IO LET X = 12.38 20 LET A$=STR$(X) will assign the string "12.38" to A$.

VAL(String)

Gives the numerical value of the string which must look like a number, reversing STR$, that is, it converts a string of digits into a numeric quantity.

The statements IO LET A = V AL("34.56") assigns the value 34.56 to the numeric variable

Converts a string of characters into a list of equivalent numeric codes and vice versa. It takes one of the following forms :

The first three of the statements IODIMN(lO) 20 LET X$="INDIAN" 30 CHANGE X$ TON 40FORl=l TON(O) 50 PRINT N(I); 60NEXTI will generate a list of 11 elements assigned as follows: N(O) N(l) N(2) N(3) N(4) 6 73 78 68 73 N(5) N(6) N(7) N(8) N(9) N(IO) 65 78 0 0 0 0 It may be noted that N(7) to N(IO) will retain the zeros in them. The last three statements would produce the following output :

CHANGE

CHANGE "NAME" TO X CHANGE X$ TO X CHANGE XTO X$ The first element in the list (for which the subscript has a value zero) will always indicate the number of characters in the string; tl)C conversion begins with the second element of the list (subscript equal to one).

A.

73 78 68 73 65 78 The reverse process is explained by the following program segment :

153

FUNCITONS AND SUBROUTINES

Function

Example

Description

70 DIM N(IO) 80 LET N(O) 4 90 FOR I =l TO N(O) 100 READ N(I) llONEXTI 120 DATA 82, 79, 83, 89 130 CHANGE N TO X$ 140PRINTX$ At line 80 the count of charcters is stored at N(O); the count is 4. The CHANGE statement will convert each element ofN, beginning with N(l), to the corresponding character.and the resulting string will be assigned to XS.Hence, the PRINT statement at line 140 will print the string ROSY.

=

In all the foregoing functions, X indicates any numeric constant, or variable (simple or subscripted); or expression, while N and I indicate numeric expressions that will be truncated to integers if not already integral. Since function references are one kind of arithmetic expression, they may appear_ as arguments in another function reference. Function calls may be embedded. Following are some more examples of built-in functions :

=

10 LETA SQR(ABS(X)) 20 lET B = INT(SQR(X(2,3))) 30 PRINTTAB(l06*(SIN(X)+l)/3 + 0.5); "*" 40 lET C Y(ABS(X+Y), ABS(X-Y))

=

Remuk: DET, NUM, LOC, LOF and most of the string functions may be implemented differently in different versions of BASIC. In addition, RND and TIM may require arguments. Ezunple 8.1 : For a trtangle such as the following,

b the law of cosines states that c ="a2 + b 2 - 2ab cos(C) where a and b can be any two adjacent sides, C is the included angle and c the opposite side. Write a program that will ask you to INPlIT a, b, and C, and then print the third side c. 10 REM PROGRAM FOR THE LAW OF COSINES 20 PRINT "INPUT LE.'11,JGTHS OF SIDEl, SIDE2, AND THE"; 30 PRINT "INCLUDED ANGLE (IN DEGREES)" 40 INPUT A, B,Cl 50 REM CONVERTCl TO RADIANS 60 LET C2 = 3.14159*Cl/180 70 LETC = SQR(A"2 + 8"2-2*A*B*COS(C2)) 80 PRINT "LENGTH OF THE THIRD SIDE IS"; C 90 END

COMPUTING WITH BASIC

154

Ezample 8.2: Given values for the rectangular coordinates x and y. write a program to find the corresponding polar coordinates rand 0, where 0 is in radians.

The required formulae ate r = follows:

'1x2 + y2

and 0 = tan- 1 (y/x). This can be programmed as

05 REM T=THETA 10 20 30 40

INPUTX, Y LET R = SQR(X*X + Y*Y)

50

PRINT "CORRESPONDING POLAR COORDINATES ARE:"; R; T

60

END

LETT= ATAN(Y/X) PRINT "RECTANGULAR COORDINATES ARE:"; X; Y

Ezample 8.3: A prime number is a number which is evenly divisible (without a remainder) only by 1 and by itself. Thus 2 is prime. 3 is prime but 4 is not prime because it is evenly divisible by 2, 5 is prime but 6 is not prime because it is evenly divisible by 2 and 3, and so on. One unsophisticated method to check if a number N is prime or not is to divide N by all the integers starting with 2 up to one less than N. If N is not divisible by any of these integers, it is prime. Another method, a little more efficient than the foregoing one, is to divide N by all integers from 2 up to the square root of N. Write a program that generates a list of all the prime numbers between 5 and 1000. As all the even integers from 4 to N are divisible by 2, they are not prime. So only the odd integers starting from 5 to 1000 are checked to find out which are prime. The folowing program has been developed. 10 REM PROGRAM FOR GENERATING A LIST OF PRIME NUMBERS 15 REM BETWEEN 5 AND 1000 PRINT "PRIME NUMBERS BE'IWEEN 5 AND 1000" 20 30 40 50 60 70

PRINT FOR I= 5 TO 1000 STEP 2 LET K = INT(SQR(I)) FORJ= 3 TOK STEP 2 IF INT(I/J)* J-1 = 0 THEN 100

80

NEXTJ

90 100 110

PRINT I; NEXT I END

Ezample 8.4: Write a program to convert inches to yards, feet, and inches. 10 20 30 40

READ I IFl=OTHEN 100 LET Y = INT(I/36)

50

LET 11 = I - 36*Y LET F = INT(Il/12)

60 70

LET 12=11 -F*l2 PRINT I; "INCHES="; Y; "YARDS"; F; "FEET'; 12; "INCHES"

80 90

GOTO 10 DATA30,267, 140,506,93,41,0

100

END

FUNCTIONS AND SUBROUTINES

155

Ezample 8.5: For each of ten pairs of numbers, find the highest common factor (HCF) and the least common multiple (LCM). The highest common factor (HCF) of two positive integers X and Y is the largest positive integer that divides both of them. For example, HCF of24 and 36 is 12. The HCF can be found by a procedure called the Euclidean algorithm : 1. Divide the larger number CO by the smaller number (s) to obtain quotient q and remainder r so that l = qs + r. (Use the INT function here.) 2. If r

* 0, then set l = s, s = r, and repeat from Step 1.

3. If r = 0, then s is the desired HCF. The least common multiple (LCM) of two posiitve integers X and Y is the smallest positive integer which is divisible by both X and Y. Further, HCF(X,Y)*LCM(X,Y) = X*Y. 100 RE~ VARIABLES: 110 REM G =GREATER OF TWO POSITIVE INTEGERS X ANDY 120 REM S =SMALLER OF X ANDY, Q =QUOTIENT 130 REM R =REMAINDER, H =HCF, AND L =LCM 140 FORI= 1TO10 150 INPUT X, Y 160 IF X