Výsledky vyhľadávania - INTRODUCTION to Computer Programming Using the BASIC Language, An (Book)

Upresniť hľadanie
  1. 1
  2. 2

    Zdroj: The Accounting Review, 1968 Apr 01. 43(2), 409-410.

    Relation: BASIC: An Introduction to Computer Programming Using the BASIC Language William F. Sharpe

    Prístupová URL adresa: https://www.jstor.org/stable/243793

  3. 3

    Popis súboru: application/pdf

    Relation: Technical report (University of Alabama at Birmingham. Department of Electrical and Computer Engineering); 2018-07-ECE-027; Technical report (Southern Methodist University. Department of Computer Science and Engineering); 88-CSE-25; Technical Report 2018-07-ECE-027 Technical Report 88-CSE-25 A Laboratory-Oriented Basic Programming Course for Engineering Students Udo W. Pooch Murat M. Tanik This technical report is a reissue of a technical reprint issued April 198 8 Department of Electrical and Computer Engineering University of Alabama at Birmingham July 2018 Technical Report 88-CSE-25 A LABORATORY-ORIENTED BASIC PROGRAMMING COURSE FOR ENGINEERING STUDENTS Udo W. Pooch Texas A&M University Murat M. Tanik Southern Methodist University Department of Computer Science and Engineering Southern Methodist University Dallas, Texas 75275-0122 April 1988 ABSTRACT The objective of this courseware is to demonstrate engineering students general methods of program development using a state-ofthe- art implementation of BASIC language (QuickBasic) as a laboratory environment and the BASIC language itself as a medium of expression. One reason for the popularity of BASIC in an age when reliable, relatively inexpensive implementations of FORTRAN, Pascal, Modula-2, LISP, Prolog, even Ada (we have developed a Computer Based Courseware in Ada as well. SMU-TR-88-CSE-16} available is the existence of a large collection of BASIC programs in various areas of science and engineering. Another is the fact that BASIC is readily available on every PC and easy to learn and, consequently, has a large following among scientists, engineers, statisticians, and general PC users. In addition, recent introductions of BASIC implementations with very practical, functional and attractive integrated environments such as Microsoft QuickBasic, TurboBasic, TrueBasic and others provide a bottom-line prototyping system for the BASIC followers. In this courseware we use Microsoft QuickBasic as our laboratory prototyping tool. In our treatment of the language elements we use Single-Step Cumulative (SSC} technique of teaching that we also used in our Pascal text (Advanced Turbo Pascal Techniques, Jan. 1988, published by Wordware Inc. Plano, Texas, 75074 -- 1- 800-231-7467). In project developments we employ the rapid prototyping methodology. TABLE OF CONTENTS 1.0 INTRODUCTION 1.1 Computer Sys terns and Languages 1.2 Hardware Components 1.3 Software Co fTll on en ts 1.4 Data Representations 1.5 External Data Storage 1.6 Problem So 1 v in g and Flowcharting 2.0 BASIC-AN INTRODUCTION 2.1 The BASIC Character Set 2.2 Statements 2.3 Variable Names 2.4 Ar itllnetic Data 2.4. 1 Integer Fonnat 2.4.2 Fixed Point Format 2.4.3 Floating Point Format 2.4.4 Aritllnetic Constants 2.5 Character Data 2. 5 .1 Character Constants 2.5.2 Quotes 2.5.3 Character Variables 3.0 ARITHMETIC EXPRESSIONS AND OPERATORS 3. 1 Arithmetic Operators 3.2 Priority Of Operators 3.3 Ari tllnet ic Expression s 3.4 Parentheses 3.5 Special case Evaluations 3.6 Expression Evaluation 3.7 Character Expressions 3.8 Relational Expressions 4.0 THE LET OR ASSIGNK:NT STATEMENT 5.0 THE DEF STATEf.ENT 6.0 THE DIK:NSION AND DATA STATEMENTS 6 .1 Arithmetic Array 6.2 Character Array 6.3 DATA Statement 6.4 READ Statement 6.5 RESTORE Statement 7.0 THE INPUT STATEK:NT 8.0 THE PRINT STATEK:NT 8. 1 Advanced PRJ NT Options 8.2 PRINT USING 9.0 THE TRANSFER OF CONTROL 9 .1 GO TO Statement 9.2 Computed GO TO 9.3 ON Statement 9.4 I F Statement 10.0 LOOP STATEMENTS 11 .0 SUBROUTINES 12.0 STOP AND END STATEMENTS 13.0 FUNCTIONS 13.1 Function, ArgliTlent and Reference 13.2 Built-in or Intrinsic Functions 13.3 Example Functions 13.1 Integer Function 13 • 2 S i gn Function 13 • 3 Abso1ute Va1u e Function 14. 0 PROGRAMMING GUIDELINES AND DEBUGGING 14.1 Criteria of Goodness 14.2 General Guidelines for Programming 14. 3 Debugging 14.3.1 Desk Checking 14.3.2 Syntax and Semantic Errors 1 4. 3. 3 Tracing 14 .4 Program Testing 14.5 SoTTE Specific Rules for Programming EXTENDED BASIC 15.0 MATRIX OPERATIONS 15 .1 Ml tr i x Manipulations 15.2 Matrix Manipulation Examples 15.3 Subscripted String Variables 16.0 FILE PROCESSING 16. 1 System Commands 16.2 Actual File Processing 16.3 An Example 17.0 THE CHANGE STATEMENT 18.0 ALPHANUMERIC MANIPULATIONS/EXTENSIONS 19.0 REVIEW QUESTIONS, AND PROGRAM EXERCISES FOR READER SOLUTIONS 20.0 ENGINEERING LABORATORY ASSIGNMENTS APPENDIX - A SAMPLE SESSION WITH MICROSOFT QUICKBASIC CHAPTER 1 INTRODUCTION 1.1 COMPUTER SYSTEMS AND LANGUAGES 1 A computer system is a collection of machines each with a specific function and a collection of support programs to aid the user. The machines which rmke up a computer system are celled hardware components, and the programs are called soft ware components. 1.2 HARDWARE COMPONENTS All computers have five basic parts: one for input, one for output, one for processing, one for control, and one for storege (the memory). While the five basic parts of a computer are common to all computers, the exact way in which they are constructed and connected together varies from one machine to the next, although the most common arrangement is the one illustrated in Figure l. l. The Central Processing Unit, called the CPU, contains the mechanisms which control (1) the flCJ.V of work through a computer system, (2) the performance of the other hardware components, and (3) the execution of the logic and arithmetic functions or the system's operation. CPU's vary in the speed with which they can access data and perform the logic and arithmetic functions. Input I Output devices, called I/0 units, serve to read data and transmit it toward the computer's memory unit and to write or display data received from the memory unit. I/0 units vary in the physical form of the data handled and in the speed with which the data is handled. Card readers, tape drives, cathode ray tubes and typewriters are a 11 examples of I/0 units. I/0 Control Units collect data from one or more input units and send it toward the memory unit, or receive data from memory and distribute it to the appropriate output units. The control unit starts and stops I/0 units and gathers, disseminates, I !\PUT OUTPLiT U:\IT lnstrut:tJons and Data Rc ~I dt~ MEMORY UJ\IT I Instructions I Results Data I .: I I : I i COI'\TROL ARITHMETIC L --- - UNIT - Al'\D LOGIC U:\IT PROCESSING UNIT Fig. 1.1 Functional description of a digital computer. The dashed lines represent the flow of control signals . 2 3 edits, or checks data, under control of the CPU. Control units comrronly transmit and receive data at rates which exceed the capacities of individual I/0 units but which are well within the data handling capabilities of the CPU. Control units vary in the type and nlJTlber of l/0 units which they can control. Data Channels provide the high speed route for data transmission between the nerrory unit and the l/0 control units. The maximum data rate of a channel usually exceeds the data rate of control units by a substantia 1 arrount. Channels vary in their maximum allowable data rate and in the nliTlber and type of control units which rr.ay use the channel simultaneously. Data storage units are c001ponents which hold data in a form such that it can be accessed by the CPU for processing, stored and subsequently retrieved by the CPU for further processing without manual intervention. Storage units are of two types, Processor Storage and Remote Storage, also called Peripheral Storage. Remote storage units cani11Jnicate with the CPU via the control units and data channels and thus are really l/0 units, although all I/0 units are not data storage units (a typewriter, or TV tube cannot store data for later retrieval by the CPU, although a tape drive or disk drive can). Remote storage units vary in the amount of data they can store, the speed with which the stored data can be accessed and the rate at which it can be transmitted or received. Processor storage units communicate directly with the CPU, bypassing channels and control units. Processor storage units are commonly referred to as Memory Units. They characteristically have very high data rates and low total storage capacity relative to Remote Storage Units. Processor Storage units vary in the account of data they can hold, the size of the Sllilll est accessible data unit and the rate at which data can be presented to or received from the CPU. 1 .3 SOFTWARE COM?ONENTS Since all the functional elements of a COmputer system work at different speed (e.g., a card reader is much slower than a processing unit) and each unit has different 4 amounts of work to do, scheduling the work and keeping track of what each unit is doing at any given time requires considerable effort. In theory, it is possible to build a control unit c001plex enough to do this, but in practice most computers use a special program called an Operating System. Logically the operating system is a master control program that supervises the control unit telling it what to do next. In other words, part of the work of the control unit has been shifted to a program the operating system. Perhaps the simplest way to explain what function the operating system performs is to say that the control unit controls the five parts of the computer during the execution of individual instructions, while the operating system controls the computer in deciding what program to run next. The contral1ing software c001ponent is the Monitor or Supervisor. This program controls the scheduled execution of all other software components, communicates with the computer operator and maintains records on programs which use the computer system. All or part of the MJnitor resides in the memory unit whenever the computer system is in operation. The language translators are programs which translate instructions to the computer fran a form written by the programmer to a fonn meaningful to the CPU. The programmer language is called the Source Language and the CPU language is called the Object Language. Typical Source Languages are FORTRAN, COBOL, RPG, and BASIC. Each language translator is a separate program written to accept a particular Source Language as input. Other common names for language Translators are Compilers and Assemblers. Language Translators reside on a remote storage device and are called into memory by the Monitor. The Linkage Editor, also called Loader, is called into core by the Monitor to link together any object language output of the language translators which need to c001rrunicate with each other. The linkage editor also loads load modules (linked object modules) into specific portions of memory and prepares them for execution. 5 The_lnput .Output Control System, called IOCS, assists language translators and other software JTDdules in setting up and performing 1/0 operations. l/0 is the process of getting the rreJTDry unit and the appropriate channel, control, and l/0 units to fu nc ti on in a complimentary ITB nn er so as to move data to or from memory. The Utility Programs are programs which perform often used but difficult to program tasks, such as Sorting. l .4 DATA REPRESENTATION For data to be processed by a computer system, it must be put in a fonn that can be read by a JTBchine. The most common machine readable form is a punched card which represents each character by a combination of twelve punches and nonpunches in a single vertical coll.ITln of the card. Each of the twelve punch positions is a binary digit (i.e. on-off, one-zero, punch-nonpunch). Data is represented on magnetic tape by eight binary digits indicated by the presence or absence of a magnetic dot. Each tape frame (eight dot positions laterally across the width of the tape) holds one character. Data is represented on magnetic disks by the presence or absence of eight magnetic dots arranged in sequence along a recording track. Each surface of the stack of disks contains a number of concentric tracks. Each track holds many characters, each represented by eight dot positions. Data is represented in a computer• s memory by a series of binary digits. Each binary value is represented by a clockwise or counter-clockwise magnetic flux induced in a small iron donut called a core or a bit. Thus memory is often called core storage, and contains thousands or millions of cores. The bits can be logically considered to be in groups of four, groups of thirty-two or any other combination. Because of this flexibility data may be represented in a computer•s memory in several different formats, inclLK:ling ( 1.) 6 Character format which uses eight bits to represent a character and is essentia11y identical to the tape or disk character representation. This eight bit group is called a byte. ( 2.) Packed decimal format uses four bits to represent a numeric digit with two digits are packed into each byte. rt>te that four binary bits can represent deci rm 1 values from zero to fifteen. In packed decimal format) bit values of ten to fifteen are invalid. ( 3.) Six bytes are required to represent a twelve dig it number such as 12,000,000,000 (i.e. two digits to the byte). This same number can be represented in four bytes by considering all 32 bits (8 bits in each of 4 bytes) as a single binary. number, where each succeeding higher order bit represents an additional power of two. This thirty-two bit representation is called the fixed pot"t binary [ format and each group of four bytes is called a word. (4.) The decimal number 185,000,000,000,000 is too large to be represented in 32 bits, however it can be represented in a specia1 format called floating point. In this format the trailing zeros of an integer or the leading zeros of a decimal fraction are represented by one byte called the exponent . The significant digits are represented by three bytes called the fraction. The entire number is represented by the three byte fraction times 16 raised to the power indicated by the exponent. Floating point is the REAL format and a+ thirty-two bit word using this format can represent numbers in the range of lo- 75 while maintaining about seven decimal digits of significance. Each group of eight bits in memory or on tape has a special ninth bit associated with it. Whenever a byte value is created by the CPU it turns the ninth bit to a one if there is an even number of one bits in the eight bit value. If the eight bit value l has an odd number of one bits the CPU sets the special bit to a zero. In this way every ninth bit byte value (8 data bits and one special bit) created by the computer will have an odd nlJllber of one bits. The bytes are said to havE' odd parity and the special bit 7 is called a parity bit. After it has been created, the parity of a byte is checked each time the byte is processed. If a hardware malfunction causes a bit to be altered the byte wil1 be out of parity and the CPU will signal an error condition and terminate processing. Data on disks are parity protected in .a similar manner . 1. 5 EXTERf'iA.L DATA STORAGE Within a data structure, characters which have composite meaning are grouped together into fields and related fields are grouped together into records. In a payroll data structure each item of information such as a name, address or rate of pay is a field. Al, of the fields pertaining to an individual employee is a record. The total collection of payroll records is called a file or a data set. A data set may be maintained as a deck of punched cards or as a series of records on a magnetic tape or magnetic disk, or some other machine readable medium. A disadvantage of a card deck data set is that each time it is to be read it must be placed in the card reader by the computer operator. A data set maintained on magnetic tape may be read or written repeatedly by the control processing unit. Thus the tape is really an extension of the computer system 1S memory. Records in a card deck data set are identified by being on separate cards. Records on a tape are separated by a gap of tape on which nothing is written. This gap is called an jnter-record gap or IRG. The standard IRG is about 3/411 of tape. The information on one card can be written on l/1011 of tape, thus a data set of short records will cause the tape to be mostly IRG 1 s. To improve tape utilization several records may be written consecutively, eliminating the intervening IRGS. This is called blocking the records and the number of records in a block is called the blocking factor. Each individual record is called a logical record and the block (i.e. all records between t\\Q IRGS) is called a physical record. If the data set is unblocked~ the physical record and the logical record are the same . 8 Records are recorded consecutively on tape; to read the seventh record the preceeding six records must first be read; thus tapes are called sequential access devices. Data cannot be effectively or econ001ically accessed in a random manner on a tape data set. M3.ny data sets such as payroll or route assignments 1 end themselves to efficient sequential processing when arranged in the proper order. A data set maintained on a magnetic disk pack is repeatedly retrievable just as on tape. A disk resident data set has the additional advantage of having each record directly accessible by moving the read mechanism, which is arm mounted, to the particular track where the requested record is written. A disk drive holds a disk pack which [ is a stack of disks. Each surface of each disk contains recording tracks. The records [ are written longitudina1ly a long each track. Each disk drive has an access arm which contains one read-write mechanism for each recording surface. The access arm is [ movable and is able to position the read-write heads over any recording track. All heads position over the same track of their respective recording surface and as the processing of one track of one surface is c001pleted the next track to be processed is the sal'l'e track on the next surface. It is much faster to electronically select the next read-write head then it is to physically move the access arm. Processing tracks in this order is called cylinder mode operation. Records can be directly accessed on a disk or can be processed sequentially, thus disk data sets are usually arranged in a particular order for sequential processing while still retaining the capability of non-sequential processing when required. A particular record on a disk is identified by an 11 addreSS 11 which is the I.D. number of the recording surface followed by the I.D. nurmer of the track on that surface followed by the I .D. number of the record on that track. 1.6 PROBELM SOLVING AND FLOWCHARTING A coJll)uter has to be instructed before it starts a process, not only how to do every step in the process, but also the sequence in which the steps are to be perforl'l'EdJ 9 All of its instructions JTlJSt be entered before the computer is allowed to start computing. A set of instructions1 to tell the computer what to do, is called a program. Each instruction in a program is called a statement. The task of preparing a problem for computer solution consists of two phases. First, the solution to the problem is formulated as a sequence of logical steps. Second, these individual steps are translated into a form which can be processed by the computer (machine language, BAS_IC, etc). It is desirable to have a standard format for representing the solution as set up in the first phase; this is provided by~fJq~ng: A flowchart is a semi graphical representation of the logical steps which comprise any process. This graphical technique serves to better illustrate the logical relationships between the individual steps. The use of standard symbols for many common steps also enhances readability and gives the user a quicker understanding of the process. Flowcharts are used for two purposes. One is as mentioned above, as an intermediate step in the solution of a problem on a computer. The second is as illustrative material accompanying a finished computer solution; this type of flowchart is often prepared after the final computer program has been written. For a flowchart to be of value in the first sense (that is, to serve as the basis for a computer program) it must obey two rules, as follows: {1) It must be complete, clear, and accurate, so that a w:Jrking computer program may be prepared from it by someone who has no knowledge of the problem being solved. (2) It must be rmchine and language independent (insofar as is possible). The standard symbols to be used in flowcharts and their meanings are as follows : _Input or output General processing ( Subroutine ca 11 ) Subroutine entry or return Termi na 1 ) 8 Off-page Connector ( opti anal) --~--A_n_n_o_t_a_t_io_n_ _______~ 10 In a flowchart the exact operation to be performed is written within the appropriate symbol. The symbols are then connected by arrows showing lines of logica1 flow. 11 arranged such that the flow is generally down the page. Input/output, call, and processi1 symbols will have one entry arrcrw and more than one exit arrow; the remaining symbols will have only one arrow, either entry or ex'ft as appropriate. To illustrate the flowcharting technique, consider the problem of solving for x in ai+6 = 0, given a and b. The flowchart for this problem is given in Figure 1 .2. ( START t = -b/a r =.rr- 1 r 2 = -r1 2 Solve ax + b • 0 Solution: x • + .r-b/a HALT Fig. 1.2 Flowchart of Example l. This halt is an error stop shO\vit:g imagi As yet another example, consider the problem of calling a subroutine (ZCOUNT) to count the number of zeroes in the first 50 cells of the array INPUT, and then to store the returned answer in ZEROES. The solution is illustrated in Figure 1.3. Arguments 1. so 2. INPUT The flowchart of the subroutine might look something like: ZCOUNT Arguments 1. N 2. Array < RETURN >--=-. Count number of zeros, store in NZEROS ! RETURN NZEROS Fig. 1.3 Fl ~chart of exalllJle 2. 0 2.0 INTRODUCTION CHAPTER 2 BASIC-AN INTRODUCTION 13 BASIC is a problem solving language. It is easy to learn and can be applied to most canputing problems-nonnurrerical as well as niJllerical problems. A BASIC program consists of the following components: ( 1) Program name (2) Numbered BASIC statements ( 3) Comments BASIC programs are temporarily or permanently stored in files through tenninals or batch input for immediate or later execution. They are filed and retrieved by their name. Each BASIC statement starts with a unique statement number, generally followed by a BASIC key word. The key word indicates the function that the statement performs (see Table 2.1). It is often handy for the programmer to be able to place comments into the program · t improve the readability of -the program. Such comments are used solely to serve as aids for the program writer or reader in keeping track of the program parts and logic, especially when the program is very lengthy. In the execution of the BASIC program, the canrrents are ignored and therefore do not affect the operation of the program. 2.1 THE BASIC CHARACTER SET 2.1.1 Alphabetic Characters Alphabetic characters in BASIC are the upper and lower case letters of the standard english alphabet (A-Z) and various alphabetic extensions (or special characters): @ ( the c an me rc i a 1 1 at 1 s i g n) # (the nuni>er or pound sign) $ ( the currency or do 11 a r s i g n) Table 2. 1 Basic Key Words Key Word REMARK LET (optional) READ MTA I NPliT PRINT STOP END GOTO IF FOR-NEXT DIM MA.T DEF GOSLE RETURN RESTORE Function C001rrent Assignment Batch Input For Supplying Terminal Input Output Input Terminating (execution) Terminating Unconditional Transfer Conditional Transfer Looping Dimensioning Arrays Matrix Functions Function Definition Transfer to Subroutine Return from Subroutine i4 Restore the original Data Stream 2.1.2 Numeric Characters. Numeric characters in BASIC are the digits 0 through 9. 2. 1. 3 Special Characters. 15 There are up to 24 special characters, depending on the termina1 type or keypunch 1imitations. Letters JTBY be typed in either upper-or lower case, if the keyboard allows both cases. In fact, all BASIC JTBY be typed in upper-case, lower-case, or a mixture of both. 2.2 STATEMENTS A BASIC program consists of a group of numbered statements, of either the executable or non-executable type, which may be intermixed. There may be a maximum nuni:>er of statements permitted in a single program, depending on the implementation. Executable statements are those statements which specify a program action (e.g., LET, GO TO, etc.). On the other hand, no executable statements are those that specify information necessary for proper program action (e.g., DATA, DIM, etc.). Every BASIC statement begins with a statement number between 0 and 99999 inclusive. Nl.ITlbers JTBY be skipped, but ITlJSt non- the-less be in order (low-to -high). Blank characters ITBY not appear before or within a statement nuni:>er. A statement and its corresponding number J together:, is ca1led a statement 1ine. Statement lines must not be split between lines, nor can there be more than one statement per print line. For example, a typical statement line might be 100 LET A= 3.2 BASIC ignores a 11 blanks {except within a PRINT statement), and so the above statement could have been written 100LETA=3. 2 16 or lOOLET A= 3.2 ( r The latter two lines are of course difficult to read, although they are equivalent r statements and mean the same thing. Spaces (or blanks} should be used wisely, especi- ( ally to ease reading. Accidental omission or insertion of blanks usually causes no problems. Once again, spaces inside quote remarks in PRINT statements will not be ignored. This will be described later. BASIC ooes not permit lines that are blank except for the line numbers. statements., with legal numbers1 are used by such statements as GO TO. 2.3 VARIABLE NAMES Such A variable is a named data item whose value is subject to change during the execution of the program. The initial value of all arithmetic variables is zero. Variable names can consist of one or two characters. If a name is a single character it must consist of a character of the extended alphabet lA-Z, @, #, $). If on the other hand it is a variable name with two characters, then a character of the extended alphabet must be follCMed by a single digit (see Figure 2.1). 2.4 ARITHMETIC DATA Arithmetic data items simply have a numeric value. All numbers are decimal also varies among implementations of the language. l A number may be integer, fixed-point or floating point, depending on the magnitude and the precision required by the program. In any format, numbers may be positive or negative. Negative numbers must be preceeded by a minus sign. The plus sign before a positive number is optional. If there is no signJ the number is treated as positive. Valid A B Cl 09 Fig. 2.1 Example Variable Names. 17 Variable Names Invalid CAP Cl2 DUMMY SAM 2. 4. 1 Integer Format Numbers in the integer format are written a!) an optional sig~ followed by a series of digits. For example, 2.4.2 Fixed-point Format 0 +2 -23 3938 18 Numbers in the fixed-point format are written a~an optional sign, optionally [ follOtJed by a string of digits. The digits following the decimal point are required, if no digit preceeds the decimal point. For example, 22. 22.00 -22.03 .3 +3.14159 2. 4. 3 Floating-point Format A floating-point number is scaled (i.e. multiplied by a power of ten), by following the integer or fixed-point number with the letter E) followed by an exponent (characteristic or power- as in scientific notation). The one or two digit exponent must be a signed or unsigned integer. The following are floating point numbers with their respective decimal equivalents. Float in g-po in t Number -. 012345 E-4 Decimal Equivalent - .0000012345 . 012345 E4 .5 E+6 5 E-7 123.45 500000 • 0000005 19 The E-4 on the first number above says to multiply the number to the left of the E by ten to the minus four (0.0001 ). Note that E4 by itself is not a legal number, since it is a legal variable name. The value two to the plus four (10000) must be represented as lE 4. Any number with the E notation must have at least one digit in front of the E. Be aware that scxne numbers may only be entered in E-fonnat. For example, with an implementation supporting a magnitude of ten to the 75 power, but which limited the number of digits in each number to a maximum of sixteen digits, a bigger value could only be entered withE-notation: 1.00000 E+20 2.4.5 Arithmetic Constant A constant is either a fixed pain~ floating-point or integer number whose value is never altered during the execution of the program. Thus, with LET X=X+l the integer one is a constant. In the next example, 13 and 3 are each constants, but the number 13/3 is not a con stan~ because it is not expressed according to one of the tht ee fonnats: LET X=X+l3/ 3 When this statement is executed, the number (13/3) will be converted to its decimal equivalent before being added to the current value of the variable X. Examples of valid and invalid constants are given in Figure 2.2. Whenever a number appears in exponential notation, the computer outputs the ·[ f o 11owing ( see Figure 2 . 3) : Va1id Constants 14 -37.3 +0.014379 49. 324371 Fig. 2.2 Valid and invalic' constants. Invalid Constants 16,321 14 A X 20 21 r Usua1 Notation Mathematical Notation BAS I C Notation 1000 1 X 103 1E+3 = 1E3 .001 1 X 10-3 lE-3 1, 000,000,000 1 X 109 1E+9 1,250,000 1.25 X 106 = 125 X 104 1.25E+6 = 125E+4 .000001234 .1234 X 10-5 = 1234 X 10-9 .1234E-5 = 1234E-9 123.456 .123456 X 103 .12345BE+3 Fig. 2.3 Example of exponentiation notation. 22 ( 1) either a space or a negative sign, depending on whether the number ;s positive or negative. t2) the first digit of the number ( 3) a decimal point (4) the remaining significant digits of the number (5) a space ( 6) the 1etter E p ) the sign + or - (8) the approximate exponent number 2.5 CHARACTER DATA Character data is any data not having a numeric value. Character data may also be hand led in the form of constants or variables. 2.5 .1 Character Constants A character constant is a string of characters enclosed in a pair of single or double quotation marks. Any character available on the input device may appear in a character constant. The following are all valid constants: 11A B c~ 112345$#1 The length of a character constant is the total number of characters, including blanks, contained within the quotes. There may be an implementation limitation on the number of characters permitted in a single character constant, as well as whether or not to uss single or double quotes. 2.5.2 . Quotes Within a Character Constant If a constant bounded by single quotes is to contain a quotation mark itself, two consecutive single quotation marks ITlJSt be entered to represent the single quote na.rk 23 in the constant. For example, The same holds true of a constant bound by double quotation marks. Representation Value 'ITS I ITS "ITS" ITS "IT 1S" IT'S I IT"S I IT'S I "ITS"' "ITS" """ITS""" "ITS" '"IT "S" I "IT'S" 2 . 5. 3 Character Variab1es Character variables are identified by a single letter of the extended alphabet followed by the dollar sign ($). A$ and$$ are two such examples. When a BASIC program is executed, the initial value of all character variables is blanks. 24 2.6 EXCERCISES 1.) Identify which of the following are valid numbers in BASIC? 6.4 003 5/8 43+1 1,234 123.456E7 5.0/4 321E-4 10248 OEO 32- 1E2.3 E2 -46 2.) Identify the following as variables, constants, functions, or none of the above. X3 7.2E-13 4 -2 SA lA 0.0 M16 2,189.3 F# Cos B$ Al $3 SQRT A12 28 3.) Write each of the following numbers in BASIC in exponential form: 1. 2378 X 10 II 1.2378 X 10-ll 62.34 X 104 62.34 X 10-4 25 CHAPTER 3 ARITHMATIC EXPRESSIONS AND OPERATORS 3. 1 ARITHMATIC OPERATORS The following arithmetic operators are valid in BASIC. • ~ Add it ion, as we 11 as the unary plus sign~ to indicate positive numbers ---~ Subtraction, as well as the unary minus signJ to indicate negative numbers Division, {A/B means A divided by B) Multiplication, (A*B means A multiplied by B) • . ~ 26 + I * •t A .,C~ ) ) ExJX)nentiation~ or to raise to the power (A**B means A raised to the--~ power B) 3.2 PRIORITY OF OPERATORS r In BASrc,operators are applied using the orders of priority from left to U right, highest to lowest, using the operation symbols. {1) **(Exponentiation) has the highest priority and is performed first. If [ two or more exponentiation operations appear in the same expression, they are evaluated in the order that they appear (from left to right). (2) Unary+ and- are second in priority and thus evaluated second. If two or more unary operators appear in the same expression, they are evaluated in the order that they appear (from left to right). (3) *and I (Multiplication and Division) are third in priority. Again if two or more multiplication and/or division operators appear in the same expression, they are evaluated in the order that they appear {from left to right). {4) +and- (Addition and Subtraction) are evaluated last in priority. Again, if multiple operators appear in the same expression, they are evaluated in the order that they appear, from left to right. 3.3 ARITHMETIC EXPRESSIONS An arithmetic expression may be an arithmetic variable, array member (to be discussed later), constant or function reference (also to be discussed later), or any combination of the above)separated by any of the operators (see Figure 3.1 ). Sorre examples are: Al 27 X3/ ( -6) SIN (8) -6.4 ( function reference) - (X**2+2) - lX**2-2) 3. 4 PARENTHESES Parentheses may be used in an expression to alter the order in which the language translator evaluates the expression. Any part of •n expression in parentheses is evaluated before any other part of the expression. For example, A-8/C is evaluated as follows: Divide 8 by C, and then subtract the result from A. However, using parenthesis this order can be altered. For example, (A-8)/C \'.Quld first subtract 8 from A, and then divide that result by C. Incidentally, A-(B/C) and A-B/C are equivalent. When putting parentheses in expressions, every left parenthesis must have a matching right parenthesis. With nested parentheses (i.e. parentheses within parentheses) the expression in the innermost set of parentheses is evaluated first. If two or more parentheses are at the same nested level, they are evaluated from left to right. 3. 5 SPECIAL CASE EVALUATIONS ( 1) In the case of exponentiation, A**8, where A is raised to the power B (a) If A=B=-0, an error will occur. ( b) If A= 0 and 8 ( 0 , an err or will occur. (c) If A(O and B is not an integer, an error occurs (i.e. do not raise a negative n LBllber to a fraction a 1 power) • Expressions Va 1 i d (A/B)*C A*B - C - c A**B Fig. 3.1 Examples of valid and invalid expressions Invalid 3(A-+£) (A/*C) X* - 3 IN - 4.5 28 (d) If A is not zero, and B=O then A**B=l. te) If A=O and B,.O, A**B=O. 29 (2) Multiplication and Addition. A*B and A+B are both co11111utative (i.e., A*B=B*A and A:B•B+A). On the other hand, they are not always associative because of low-order rounding errors. I.e., A*(B*C) does not always give the same result as (A*B}*C, just as A+(B+C} does not always result in the same result as (A+B)+C. (3) Division. A/B is defined as A divided by B. If 8=0, obviously an error will resu1t . (4) There are no special conditions that apply to subtraction (A-B). ( 5) Unary Opera tors. Positive and negative unary opera tors may be used in two situations: la) Following a left parenthesis and preceeding an arithmetic expression. lb) As the left most character in an entire expression which is not preceeded by an operator. For example, -A+ t-(B)) 8**(-2) -A+-8 B**-2 J J valid invalid Caution has to be taken in performing exponentiation. Negative numbers can only be raised to integer powers. Positive numbers can either be raised to integer or real powers. If an exponent is not an integer, then the log functions are used during the evaluation. A**B= Antilog10 (B· log10 A) Since the log 10 of a negative number does not exist, negative numbers can be raised to integer numbers only. 3. 6 EXPRESSION EVALUATION The fo 11 owing examples are to illustrate successive steps in express ion evaluation as outlined usi.ng .the above .- rules. let .A=2, B=3, C=6 ( 1) Expression -A**3 + C/6*2. 5 Evaluation -2**2 + 6/3*2.5 ( 2 ) Expression Evaluation ( 3 ) Expression Evaluation ( 4) Expression -8 + 6/3*2. 5 -8 + 2 *2. 5 -8 + 5 -3.0 ( -A** 3) + C /B *2 • 5 (-2**3) + 6/3*2.5 -8 + 6/3*2.5 -8 + 2 *2.5 -8 + 5 -3.0 -A** ( 3 +C /8 ) * 2. 5 -2**( 3+2) ** 2. 5 -2** 5 *2 .5 -32 *2.5 -80.0 -A**((3+C)/B)* 2.5 -2**((3+6)/3)* 2.5 -2**(9/3) * 2.5 -2** 3 -8 -20.0 * 2.5 * 2.5 30 r 31 3.7 CHARACTER EXPRESS IONS A character expression is composed of a character variable, a character constant~ or a subscripted character array reference (to be discussed later). For example, LET A$= 'ABCDEFG' IF D$ = C$ THEN 20 The only operators ever associated with character expressions are the relational operators (and the 11=11 operator used with LET) described below. The following are therefore inva1id character express ions: A$ + 11 I NG" 'STATEMENT' - 'MENT' 3.8 RELATIONAL EXPRESSIONS A relational expression tests the relationship between two arithmetic or two character expressions. The expressions that are to be compared are evaluated and then compared according to the relational operator that is specified . Then, according to the result, the relational expression is either satisfied (True) or not satisfied {False). These relational expressions rray only appear as part of an IF statement. Relationa1 0perator --- Definition Not equal equa1 greater than or equal to less than or equal to . greater than less then The expressions that are to be compared must be of the same data type; that is, they must be both character or both arithmetic data types. Furthermore, only two expressions 32 may be compared in a single relational expression. In general, a relation consists of an expression, followed by any relational symbol, followed by another expression. For example, (A+B*C)~ (D*C**2) I ABLE I = 'BALL I 33 3.9 EXCERCISES 1.) The following arithmetic expressions contain at least one error . Write the correct expression. a) ( x+y) 3 b) a·b c+2 c) ( ~ )n-1 y d) a + Ced -b- e.feg e) a1/3 ~ b2- ., f) 4ac g) ( 1 +H) (1- F) 3F H5- X 2.) Write BASIC arithmetic expressions for each of the following. a) b) c) d) e) f) g) h) i ) j) X2 + y -3 3 -(i-1) X (Sin 2a) 1/2 Cos2 q-t\) ~ lf r3 3 a + b c+d a [x+b ( x+c )1 a - . 5 x+y xz a x+y + 3.5 2 (xy -1 ) 34 35 3.) What is the value of each of the following. a) 2.0 * 4.0 + 6.0 ** 212.0 b) - 5.0 t 2 + 2.015.0 * 10 c) 2. f2. t 3. + 7.121 d) ( 2. t ( 2. t 3. ) + 7)12. e) ( - 5.0) t 2 + 2.0 I (5.0 * 10 ) f) ( - 2 ) ** 4 g) 7 + 81 10 h) 4 f 3- SQR ( 13 + ( 812 * 3 )) i) SQR (4) + 20- 1612t 3 j) (2 f (412) + 4 ) I ( 1 + 3) k) 2 ' 412 + 4 I 1 + 3 36 CHAPTER 4 THE LET OR ASSIGNMENT STATEMENT The LET statement, or assignment statement, assigns the value of an expression to one or more variables. The general format of the LET statement is given by ( see Figure 4 .l ) : LET X = exp where exp is an expression, variable, or numeric literal, whose value is assigned to the variable X. When the LET statement is executed, the value of exp is calculated, and is assigned to the specified variable (in the above case to X) Character constants containing less than 18 characters are padde~on the right with blanks)to obtain a length of 18 characters before assigned to the character variables. For example, assume that the following statement was coded in a BASIC program: 1 0 LET A$ = I CAT I The evaluated expression 'CAT' would be expanded to: I CAT --- - 1 where the hyphens (-) indicate 15 blank characters, and the final length of the expression would be 18 characters. This expression is then assigned to the variable A$. The length of the character constant is implementation dependent. Character constants containing JJDre than 18 characters are truncated on the rightJ so as to leave 18 characters. Thus if a statement was written as: 10 LET A$ = 11 ABCDEF~IJKLMNOPQRSTUVWXYl I The resulting value of A$ would be: 11ABCDE FGHI JKLMNOPQ R I LET The word LET Equal sign r A = X + Y ~ Available name that receives the value A number, a variable name, or an expression Fig. 4.1 The general format of the LET statement. 37 38 Character variables containing the null string (i.e. no characters) are assigned 18 blank characters. For example: 10 LET A$ = II is the same as: 10 LET A$ = • --- where the hyphens represent 18 blanks. The following are general rules that apply to the LET statement. 1) Data values to the right of the equal sign(=) must be of the same type (either arithmetic or character) as the variables to which they are assigned. 2) Subscripted references to array members are permitted in the assignment statement, but unsubscripted array references may appear only in the W\T assignment statement {to be discussed later). 3) The maximum number permitted on the left side of the equal sign in a multiple assignment statement depends on the implementation of the BASIC language. Multiple assignments of variables are also possible. For example, instead of writing: 10 LET X= 2*Y + 10 20 LET Z = 2*Y + 10 30 LET W = 2 *Y + 1 0 The statements could have been written as: 10 LET X,Z,W = 2*Y + 10 or 10 LET X=Z=W= 2*Y+l0 In either case, the computed value of 2 *Y + 10 would be assigned to the variables X, Z, and W. There is one general rules that applies to the multiple assignments: The value of the expression on the right side is assigned to the variables starting from the leftrrost variable- in a left to right fashion. Note that the general rules for the assignment or LET statement also apply to multiple assig1111ents. If the statements were written as follows: 20 LET X=9 30 LET Y(X}=2 40 LET X,Y(X)= X/Y(X) or 40 LET X=Y(X)=X/Y(X) 39 where Y is a one-dimensior.al arithmetic array, and the slash(/) indicates division. The values of X, the subscript X (in Y(X)), and Y(X) are 4.5, 4.5, 4.5 respectively. Although the value of the subscript X is assigned to be 4.5, upon execution of the assignment of Y(X), the value of X w1ll be truncated to the integer 4. Thus, the fourth meni>er of array Y is set to the value 4.5. If statement 40 had been instead written as: 40 LET Y(X), X= X/Y(X) or 40 LET Y(X)=X=X/Y(X) the resulting values of X, the subscript X, and the value of Y(X) would be 4.5, 9, and 4. 5 respectively. Note, on some BASIC implementations, the key word LET is optional, si nee the statement context is sufficient to determine the function that has to be performed. Examples [ of valid and invalid replacement statements are given in Figure 4.2. Replacement Statement Valid Invalid 5 LET X = 3. 123 10 LET X + B = 3 10 LET C1 = (A+B)/C 20 LET 1 = A 20 LET Z =At 2 A = INT(A) 30 LET K = SQR(Z) 40 LET Z4B = 17 50 LET 11A11 = B/C 60 LET A$ = •sAM 70 LET B = IIJOEII 80 LET A$ = C$*0 90 LET A1 = 2,200 Fig. 4.2 ExafTl'les of valid and invalid replacement statements. 40 [ 41 4.1 EXCERCISES 1) Write the following algebraic equations as LET statements. a) x = 3y2 + 2y - 3 b) a=Wz c) w + 2) w - 8 e) 2 3 4 X = al c + a2 c + a3 c + ~ c f) X = i ( 3a 3 b 12c3) 7 g) F = (A+ Bt D + 3 h) G = (10 A) 30 B - C 2) Write the following algebraic equations as LET statements with a minimum number 3) of parentheses. a) b) c) d) e) f) a = b + c d d = ( x-y)2 + ( a-b)2 c = y = Cos2 (b) + Sin2 (b) y = c (a)2 - 3a b x = a - b + ced/ fg Eliminate unnecessary parentheses in the following LET statements. a) 100 LET A = ( ( X+ y ) - Z) * ( X/ Y ) t Z b) 100 LET X = ((A)* ( stc )tD)/E c) 100 LET A = ( X+Z) I ( Y-((X+Y)- 2 * (Z/K))) d) 100 LET z = (((( X+Y) t ( K+1)) * H4) * 2+3)/(A-4) e) 100 LET c = ( A+B ) + ( A-D )/(3) f) 100 LET D = ( X+(Y) * 2 ) + ( A/( B+l)) g) 100 LET X = ( A+B )/(SQR (X+Y/(Z))) * (X) 42 43 4) Consider the following BASIC program. What would be the values of A and I? a) 10 LET I = 1 b) 20 LET A = I c) 30 LET c = 2.5 d) 40 LET I = A+C e) 50 LET J = c f) 60 LET A = I+J 5) Why are the following forms of the LET statement incorrect? Identify which are valid or invalid? a) 100 LET Z28 = A b) 100 LET A = B/-C * D c) 100 LET A = -B -B * B d) 100 LET X = E**M + M**E e) 100 LET X = AB + C/E f) 100 LET y = D- E/1.5 + 6.7/A/X g) 100 LET z = M**I + E**M h) 100 LET A = -B -B* -B i ) 100 LET X = -X j) 100 LET Y3 = A+B+3/4 k) 100 LET SQR(X) = 16 1) 100 LET Z1 = Z2 +YA * (3+X) m) 100 LET X = X (X+ 1) n) 100 LET z = ( ( A+B ) * C) *D t 3 o) 100 LET A = (B/C * ((D+£)) +1 44 5.) Con't p) 100 LET y = z·w - 7 q) 100 LET -Z=Z+3 r) 100 LET 2*8+6 = A s) 100 LET C = ( K+ 4 ) ( M- 8) 6.) Given the following statements, show the result after each LET statement has been executed. a) 10 LET A = 1. 0 b) 20 LET B = 2.0 c) 30 LET N = 4 d) 40 LET X = A+B e) 50 LET Y = A*B f) 60 LET Z = A/B g) 70 LET W = X+Y -z h) 80 LET X = X*Y t B/N i ) 90 LET C=Y1Bt2 j) 100 LET c = (Y f B) t 2 k) 110 LET 0 = (((A*2.0*B) /N) t 3) -1.0 1 ) 120 LET K = -(N) m) 130 LET N = -(K)* -(N) 7.) Write each of these equations as BASIC statements. a) ¢= A+rn= b) a = ~b + rc c) s = \ t + u t t -, d) t = Sin a + Cos b e) d = 1 n (f) 8.) Which of the following multiple assignment statements are illegal in BASIC? a) 100 b) 100 c) 100 d) 100 LET LET LET LET A = B = C+D+2 A = B+2 =C =D A = 2 =B2 =3 A = B+C =02 45 CHAPTER 5.0 THE DEF STATH£NT 46 The DEF statement is a non-executable descriptive statement. It defines a user- r written function that can be referred to anywhere in the program in which it is contained. Twenty six (26) user-written functions rmy be introduced f this number is implementation dependent). ·Each DEF introduces (or defines) a single function. The general format is: DEF FNA ( V ) = ARI 11-lf-1: TIC EXPRESS ION where A is any letter in the alphabet {A through Z), and V is a single arithmetic variable name , called the durrmy ovariable. The user-written function is referenced by FNA(X), where FNA is the name of the function, and X is an arithmetic expression called the argument. When a reference to a function is encountered in an expression at execution time, the current value of the argll!lent (X) is substituted for each occurrence, if~any, of the dummy variable (V) in the arithmetic expression of the corresponding DEF statement. The expression is then evaluated and the result is assigned as the value of the function reference in the expression in which it appears. For :example, lO LET Y = 10 20 DEF FNA(X) = X**3/2 30 LET Z = FNA (Y) and the value of Z is 500. If the di.ITlmy variable does not occur in the arithmetic expression of the DEF statement, it will have no effect on the value of the function. For example, 40 LET Y = 2 50 DEF FNZ(X) = Y**3 60 LETR=FNZ(lO) 47 with R having the value of eight. A function may be defined anywhere in a BASIC program, but must be defined only once. It can include any combination of other functions, even those defined by other DEF statements, but it cannot include a reference to itself or to a function that refers back to it. For example, 70 LET Y; Z 80 LET:-R = FNC(Y) +23 90 DEF FNB(X) = 5*X**2+27 100 DEF FNC(X) = FNB(X)~X The value of R will be 72. The evaluation comes about as follows: 80 LET R = FNC(2) + 23 = FNB{2) + 2 + 23 = 5*2**2 + 27 + 2 + 23 = 20 + 27 + 2 + 23 = 72 On most systemsJ user-defined functions have the following characteristics. ( 1) The argument( s) may be any numerical expression or variable when the function is used. In the DEF statement, however, the argument (s) must be an unsubscripted variable. ( 2) Functions may have any number of arguments, or none at all. ( 3) A DEF statement may contain other functions which are either user defined or built-in functions. (4) The DEF statement may appear anywhere in a program. (5) The Definition must appear on one line. (6) The DEF statement may contain variables other than the functions arguments. All variables which are not arguments of the function have their 48 current value. Thus these variables can be given new values before the function is used again. For example, 10 DEF FNA(A,B) = SIN (A-B)*(A-8) 20 DE F F NB (X, Y , Z) = FNA (X, Y) + F NA ( Y , Z) 30 PRINT FNB(l,2,4) 40 END Sane BASIC implementations provide definitions of functions which require more than one 1ine. The multiline function definition begins with the statement DEF FN*( X) and ends with the statement ~ * can be replaced by any letter of the alphabet. Thus, there can be a maximum of 26 different functions in one program. The multiline definition is recognized by the absence of an equal sign in the DEF statement. The statement FNEND (an abbreviation for Function End) indicates the end of the nultil ine function definition. Again, as in the case for single line function definition, the multiline function definition IllY appear anywhere in the program. Note that we cannot exit from a multiline function definition by a GO TO , IF-THEN, or ON-GO TO statement. We can exit only by the statement FNEND. Also note that a DEF statement may not be placed inside a multiline function definition. A function is similar to a subroutine in that in each case contra 1 branches to a particular section of the program, executes that part of code, and then returns to where it left off. There are, however, several differences between the two: (1) There is a numerical value associated with a function, whereas a subroutine has no such value. 49 (2) Since a function has a definite value, it can be used in expressions. ( 3) A function usually has arguments. Functions, like subroutines, are used to avoid repetition in a program. Fumtions smuld be used when the same operation must be perfonned on different values, a m:rr.~ber of tii'TES. Examples of valid and invalid function definitions are given in Figure 5.1. 50 Function Definitions Valid Invalid 10 DEF FNA( X) = INT(X)/10 10 DEF FW1.$(X) = (B$;C$) 20 DEF FNB(X) = INT(l+(10*RND(-1))) 20 DEF FNB = A*B 30 DEF FNC( X) = A *B /C 30 FNC(X) = SQR(X/10) Fig. 5.1 Examples of valid and invalid function definitions. 51 5.1 EXCERCISES What is wrong with each of the following statements? 100 DEF RTL (X, Y) = (X+1.3) /2.7 100 DEF SAM (B) = (A+B)/(A-5.8) 100 DEF FNA (X) = II THIS L/NCE IS ILLEGAL" 100 DEF FNZ (X) = A*B/C 100 DEF FNB = A*B/C 100 FNA (X) = !NT (X/25+0. 5) 100 PRINT "INPUT"; FNA(X) 52 CHAPTER 6.0 THE DIMENSION AND DATA STATEmENTS size dimensions of or arrays. 6.1 ARITHMETIC ARRAYS The dimension statement (DIM) explicitly defines the An array is a collection of similar data that is referred to by a single name. BASIC arrays may E" ;either -fi)ne-()o -tw(')-!timensi on a l. A-oner.rdimens-i ona 1 ·arr error condition resu1ts . ( 2) A RESTORE statement for an a 1 ready restored Table is ignored . In other '.«>rds ! if two RESTORE statements were executed one after another, the second RESlDRE statement will be ignored. For example, 10 READ A,B,C,D,E,F 20 READ G,H,I,J,K,L 30 READ X, Y 40 RESTORE 50 READ 100 DATA 110 DATA 120 DATA M,N,P 1,2,3,4,5,6 7,8,9, 10,11,12 13,14,15,16,17,18 The variables M,N,P will contain 1,2,3 respectively. 63 64 CHAPTER 7.0 INPUT STATEMENTS Before continuing with the BASIC 1anguage, it might be useful to discuss 11interactive- computing11, the environment in which BASIC is most often found. Interactive-computing (or time sharing) is an environment designed for small to moderately-sized problems, as well as for the debugging of any program. This environment allows a large number of users to interact with terminals to the c001puter and work on problems simultaneously. Short job requests receive almost instantaneous service, at the detriment of longer running jobs. The users type their programs directly via the terminals into the computer, eliminating the necessity for punched cards or tapes. A master program, called the supervisor or executive system, keeps track of what each user is doing and decides who should be served next, and for how long. One feature useful in interactive-computing is the ability to complete short problems and programs within minutes, and during the debugging stages, obtain error messages almost instantaneously. The input statement is used just like a READ statement, except that the data or . information is typed in by the user from the terminal, rather than having to put a [ DATA statement in the program. This allows the user to supply the data after seeing [ some partia1 results. The real use of real-time input (input during the time that the program is executing) is to place an input statement in the program whenever more information is needed. When the c001puter reaches an input statement during program execution, it stops running the program (and saves everything it has done up to that point), types a question mark on the user's terminal, and waits for the user to supply the necessary data. Then the program execution proceeds from where it was interrupted or last stopped 65 Since the input statement signals to the user only with a question marks it is helpful to use a PRINT statement to print out a label or some sort of information. preceding ·the input statement in order to identify the data that is being requested. This is particularly important when more than one input statement occurs in a program. The general format of the input statement is: INPUT VlsV2, .•.• , VN where Vl, V2, . ' VN are input variables (see Figure 7.1). When an input statement is encountered at execution time, it causes a question mark to be printed out at the terminal and program execution to be temporarily interrupted. The user then enters a list of values which are assigned, in order of appearance, to the variables specified in the input statement. When the complete 1ist has been entered, signaled by a carriage return, the program execution resumes. Subscripts of array variables in the input statement are evaluated as they occur. Thus an assigned variable in an input statement may be used subsequently as the subscript of another variable in the same INPUT statement. Character constants entered at the terminal are treated just like in the READ staterrent (Padded, truncated, or null). Arithmetic data values are assigned to variables in the form (short or long) which has been specified by the program. Thus, long-form values, entered at the terminal during the execution of a program for which short-form arithnetic has been specified1 are truncated to the implemented-defined number of significant digits for the short form (at least six digits} 1 before being assigned. Similarly, short-form values entered at the terminal during execution of a program for which long-form arithmetic has been specified are zero-filled to the implementation-defined number of digits for the long form (at least eleven~ before being assigned. 66 INPUT the word IN) A list of variable names Fig. 7.1 The general fonnat of the INPUT statement. 67 When an INPUT statement is executed immediately after a PRINT statement in which the final delimiter is a comma or semicolon, the question mark is printed directly following the last data item on the same print line. In all other cases, the question mark appears as the first character on the next print line. The fell owing rules apply to the INPUT statement: (l) Each value entered must be of the same data type (either arithmetic or character) as the corresponding variable in the input statement. Data types may however be mixed within the same statement. l2) Each value entered must be separated from the next by a comma. Two consecutive commas are treated as an error. A carriage return ends the series of values entered. (3) Only a single line of input may be entered in response to an input statement. ( 4) A character constant in the input stream rrust be bounded by a pair of single or double quotation marks (implementation dependent). (5) The number of values entered at ·execution time must be equal to the number of variables specified in the input statement. ( 6) The procedure for retry or re-entry of data, after an error, varies among the various BASIC Implementations. In the following example, assume the program was coded as: 20 READ A$, R(3), X, Y{X) I 40 INPUT A$, R{3), X, Y(X) 100 DATA 'CAT' , 2El0, 123, .123 When statement 20 is executed, the variables A$, R(3), X, and Y(X) will contain the 68 values 'CAT --- ', 2 ElO, 123, and .123 respectively. When statement 40 is executed, the program is interrupted and a question mark is displayed on the terminal . The user will then type in the values desired and enter the values by pressing the carriage return on the termina1. Thus the 1ine would appear as: ? 'DOG' 4 E-7, 8, .0123 The variables A$, R(3), X, and Y{X) will now contain the values lDOG --- ', 4 l-7, 8, and 0.0123 respectively. Examples of valid and invalid lNPUT statements are given in Figure 7.2. Input Statements Valid Invalid 10 INPUT A, 8$ , C , D $ 10 INPUT A 8 20 INPUT SQR(A) Fig. 7.2 Examples of valid and invalid INPUT statements. 69 70 CHAPTER 8.0 THE PRINT STATEmeNT The PRINT statement is the instruction that allows the programmer to print values of specified arithmetic and character expressions. The format of the printed values is standardized, but the programmer can control the spacing between certain values on the printed line. A print statement has the following basic format: I PRII'IT Vl • V2, • • • • • • VN 1 where Vl, V2, •••• VN, can be arithmetic expressions, simple character variables, character array variables, and literal strings (see Figure 8.1). For example, PRINT X, Y, 'DOG 1 , 1CAT 1 , A$, B$(2) In the above example, the values of X andY, the words (literals) DOG and CAT, and the values of A$ and B$(2.) will all be printed on one line in the order that they appear in the 1 is t. There are two ways to control spacing along a 1 ine. The comma between variables means that they are to be printed on one line with the spacing detennined by the system. If the comma between Y and 1 DOG' is omitted, the values are concatenated to each other. The absence of the comma between two expressions is called a null delimiter and may be used when one of the expressions is a character constant (literal string). Two consecutive character constants or two expressions of which neither is a character constant, must be separated by a comma. For example, LET X = 1. 00 PRINT I X-IS I X PRINT the word PRINT 11A VALUE =11 A , 4, A+B A qiOted · message, variable name, numeric value, and/or an expression, or none of these. Fig. 8.1 The general form of the PRINT statement. 71 72 wil1 cause the printed 1ine to 1ook 1ike this X IS 1.00 On the other hand LET X = 1.00 p RI NT I X- I s I ' X wil1 cause the printed 1ine to 1 oak X IS --- 1 .00 If a comma had been added after B$(2), the next print statement would start on the sane line. A blank at the end of the li.st indicates that no more is to be printed on that line. For example PRINT N, PRINT Y will cause values for N and Y both to be printed on the same 1ine, although they are printed with two print statements. The null delimiter can only be used to separate two expressions when one and only one of the variables is a character constant. Note, a blank line may be printed by using a PRINT statement which has no variables as arguments. Examples of valid [ and invalid PRINT statements are given in Figure 8.2. For printing output on most BASIC systems, the page (or screen) if a CRT device) is divided into five print zones. There are approximately 15 spaces, or print position each print zone; the exact number depends on the particular installations. Figure 8. 3 illustrates the typica1 page format. PRINT Statement Va1id 10 PRINT "A=•, A, "B=", B 10 20 PRINT A; B; C; D; E 20 30 PRINT "SUM=", A+B 30 40 PRINT "VALUE OF MATRIX" 40 50 PRINT 10+20, "OUTPUT" 50 Fig. 8. 2 Examples of valid and invalid PRINT statements. 73 Invalid DATA -10. 5, "SAM", 5 PRINT A$ PRINT "SAM PRINT 8$, "SAM" C$ PRINT , OUTPUT 74 1 16 31 46 60 Zone 1 Zone 2 Zone 3 Zone 4 Zone 5 Fig. 8.3 Example of a typical page format. As values appear in the PRINT statement, they are printed left to right per line, with the data printed at the left side of the PRINT zone. The use of an additional comma. (on sane systems} on the PRINT statement indicates that a print zone is to be skipped. Another technique is to just print out a blank character in that zone. To give the programmer the option of closely spaced printing, BASIC permits the use of a semicolon to separate data items. Depending on the system that is implemented, fewer spaces are allocated per zone. The comma and semicolon may be used in the same PRINT statement to condense some data items and to separate others. Either the comma or the semicolon may be used at the end of a PRINT statement to suppress a line feed. Numeric data items separated by semicolons in a PRINT statement are printed out The aJTDunt of space reserved for each piece according to a variable spacing pa ttern. of numeric data depends on the number of digits each number has1 and the BASIC implementation One commonly used zone arrangement is shown below. No. of characters in field 1-4 5-7 8-10 11-13 8.1 ADVANCED Print OPTIONS (EXTENDED BASIC ONLY) Length of zone 6 9 12 15 75 On many BASIC systems, it is possible to achieve even greater control over the way values are printed than by simply using the comma or the semicolon. The TAB option specifies that a value is to begin in a certain print position. PRINT TAB ( N) STA TEM:NTS In BASIC, the print spaces are labeled 0 through 74, from left to right. The statement PRINT TAB(N) instructs the computer to skip to the Nth space on the output device. The argument N of the PRINT TAB(N) statement may be any nonnegative number or numerical expression. If 75~ N~l50, then TAB(N) = TAB(N-75); if 150~N ol s # # Description and Rules INTEGER A string of consecutive pound signs where the value may be printed: (a) values are truncated if not integral (b) values are printed right justified (c) a place for minus sign-must be allowed. (d) the field may be widened to the right if the integer is too big. DECIMIL A string of pound signs with one decima1 point included (not as the first character Digits may be printed at the #. (a) values are rounded to fit the field (b) the decimal point is printed where it appears and the other digits are printed correspondingly. (c) a place for the minus sign must be allowed (d) the field may be shifted right and widened if the number is too big •. EXPONENT A decimal field followed by four up-arrow The exponent part (for example, E+03l> E-12) is printed where the up-arrows appear and the properly adjusted and rounded value is printed in the decimal field. (a) a place for a minus sign lll.ISt be allowed. Table 8.1 eon•t. Spec ia 1 Symbo1s arbitrary except for quote marks single apostrophe arbitrary except for no # II ·t 80 Description and Rules (b) the second (from left) pound sign position will have a non-zero value printed. STRING A string of characters where the first and last are quote marks and no other quote marks appear. A character may be printed at each position in the string, including the first and last. ("a) the characters are printed left justified. (b) if the string value is shorter than the field width, then blanks are printed. (c) if the string value is longer than the field, then it is truncated on the right. STRING The first (leftmost} character of the string is printed in the position occupied by the apostrophe. LITERAL The characters appearing are printed exactly as they appear (literally} and in the corresponding position. Note the position of the colon in statement 30, as well as the two trailing zeros. ill!! t iDe out~t. Trailing decimal positions are always zero filled (padded). {3) If the fonnat specification is such that the value cannot fit into the space allowed, most BASIC systems output asterisks to indicate this error. 1 0 LET X = 1. 23 4 20 PRINT USING 30, X 30 . # # 40 END Output: *** (4) Extra output fields that are not needed are ignored by the systan. 10 LET X = 1. 234 20 PRINT USING 30, X 30 # • # # # # # 40 END Output: 1. 23 On the other hand, if a required output image is not given, the system outputs a string of asterisks {the number of which is implementation dependent). 10 LET X = 1.234 20 LET Y = 5 • 6 78 30 PRINT USING 40, X, Y 40 # • # # 50 END Output: 1.23 * * * * 82 (5) An example of characters being printed literally, except for{#), ( ), and apostrophes is given next. 1 0 P RI NT US IN G 2 0 20 : ABCDEFGYIJKLMNOPQRSTUVWXYZ 0123456789! 11 $%&(.)* : =- 30 END Output: ABC DEFGHIJKLMNOPQRSTUVWXYZ 0123456789! II$%&<>*:=- Several additional facts concerning the PRINT USING statement, so far not encountered, include: ll} The output image may appear anywhere in the program. It need not immediately follow the PRINT USING. t 2) If the value to be outputted is negative, an extra pound sign must be allowed for a minus sign. (3) For output of exponential values, at least one digit must be requested [_ ahead of the decimal point. If a value is negative, two pound signs must be given ahead of the decimal point. ( 6) 10 LET X = - 17.43 20 LET y = 12 .28 30 LET z = X * y 40 LET w = - 17.43 * 0.0001 50 PRINT USING 60, X, y' z, w 60 : #.##fftt # .###f11t ##.##fflt ##. #### tfft 70 END Output: ******** 1. 228E 01 -2. 14E 02 -1 .743E-03 83 Note, the X value did not get printed because we did not allow for the negative sign. Furthennore if four arrows are not given, incorrect output would be generated. ( 7) 10 LET X = - 17. 43 20 LET Y = · 12 • 2 8 30 LET Z = X * Y 40 LET W = - 17.43 * 0.0001 50 PRINT USING 60, X, Y, Z, W 6 0 : # . # # 11'1 # . # # # tt # # # # . # # 1 # # . # # # # tt 70 END Output: * * * * 1 ti' * * * * * t t -214.04 t -0. 0017tt The next set of examples are given to show the output provided by alphanumeric variables . ( 8) 10 LET A$ = 11ALPHANUME Rl C OUTPUT" 20 : 1 LLLLLLLLLLLLLLLLLLL 3 0 P RI NT US IN G 2 0, A$ 40 END Output: ALPHANUMERIC OUTPUT The string of L's has to be sufficiently large to accommodate the output, or else only partial output results. R's would right adjust the output, while c•s would cause centering. 84 ( 9) 10 LET A$ = "LEFT" 20 LET B$ = "RIGHT" 30 LET C$ = "CENTER II 40 LET D$ = 11 IMAGE STATEMENT IN EXTENDED BASIC 11 50 PRINT 11 01234567890123456789 012345678" 60 P RI NT USING 7 0, A$ , B $, C$ 70 : I LLLLLL I RRRRRR I cccccccccccc 80 PRINT USING 90, D$ 90 IE 100 PRINT USING 110 110 : MAY BE USED FOR HEADINGS OR DESCRIPTIONS 120 END Output: 012345678901234567890123456789012345678 LEFT RI GLJT CENTER IMAGE STATEMENT IN EXTENDED BASIC MAY BE USED FOR HEADINGS OR DESCRIPTIONS On some implementations of BASIC1 the general form of the PRINT statement is I P RI NT ( e xp) I where exp contains an ordered list of carriage controls, variable names, arithmetic ( expressions, messages, and/or output controls. The only difference between the above and the previous version of the PRINT statement is the carriage control characters, which occur as first items in the output list of the PRINT statement. Carriage control characters control the positioning of the output display. These controls are embedded in quotation marks, 85 just 1ike string constants and messages . Some of the more commonly used carriage contro1s inc1ude : II II ( b 1 an k) single spacing IIQII (zero) double spacing 11_11 ( minus) triple spacing 11111 (one) - skip to top of next page on batch device or skip 6 1ines on a terminal device. If the first i tern of a PRINT statement is a string that contains one of these output controls, then the control is executed and is not outputted with the other string characters. If the list of a PRINT statement does not contain an output control character, then single spacing is assumed. Again, the comma is the nominal separator between items in the list. It causes the movement of the output device to the next printing zone. A comma behind the last list item in the PRINT statement deletes the carriage return. Shorter zones (1ess than 15 spaces) can be obtained by the use of semicolons. The actua1 zone 1engths are system implementation dependent. The most frequently used output controls are TAB (the output tab function), the l semicolon to produce packed output, the comma or the normal list item separator. One Additional output control is the colon(:). The colon between tv1o list items in the PRINT 1ist is used to give a carriage return. The colon may also occur at the end of a PRINT 1ist. 86 8.3 EXCERCISES 1.) What is printed by the following programs? a) 100 READ A, A 110 PRINT A 120 GO TO 100 130 DATA 1, 2, 3' 4 140 END b) 100 FOR R = 1 TO 10 STEP 3 110 IF N = 3 THEN 50 120 PRINT R; 130 NEXT R 140 END c) 100 FOR R = 1 TO 10 STEP 3 110 LET R = R+2 120 PRINT R 130 NEXT R 140 END d) 100 M = 3 110 N = 7 120 PRINT N, M 130 END 87 e) 100 FOR K = 1 TO 3 110 READ A, B 120 PRINT A, B 130 RESTORE 140 NEXT K 150 DATA 4, 3, 2, 1, 8 160 END f) 100 LET A = 10 110 LET B = -20 120 LET c = 30 130 PRINT II C="; c' "A=''; A, "B= II; B 140 END g) 100 READ X,Y,Z 110 W = S+Y - z 120 PRINT w 130 DATA 3 140 DATA 4 150 DATA 5 160 END 2.) Write a program that outputs a vertical line of asterisks. 3.) Write a program that outputs a horizontal line of asterisks. 4.) Write a program that outputs a diagonal line of asterisks. 5.) Write a program that will use a DATA statement and outputs the letters of the alphabet in a horizontal line. 6.) Write a program that plots the parabola y = x2. 7.) Write a program that produces the letter W. The output should look something like X X X X X X X X X X ·x X~ ~X 88 89 8.) What is wrong with each of the following statements? 100 PRINT THE ANSWER IS, A 100 PRINT 11 TOTAL SALES 100 PRINT 11 THE ANSWER IS, All 100 PRINT ABC 100 PRINT A B c 100 PRINT A$ * 8$ 100 PRINT IIP,RII 100 PRINT 11 THE VALUE OF N', IS;A 100 PRINT 3 t 4, 47-18, D$+4, N*7 9.} Correct the errors in each of the following statements. a) 100 READ N$ 110 DATA 18 b) 100 READ N 110 DATA M c) 100 DATA 491 110 READ A,B d) 100 READ K$, L$, M$ 110 DATA 1, 2, 3 e) 100 READ z, y 110 DATA 31 16 10.) Correct the errors in each of the following. a) 100 PRINT "test", TAB ( 8) , "RUN'' b) 100 PRINT USING 200, A, B 200 ### ### c) 100 PRINT "DATA DESCRIPTION"; TAB(6); A$ d) 100 PRINT A; TAB(6); B; TAB(6); C e) 100 PRINT USING 110, A$ 110 LLLLLLLLLL 11.) What is wrong with each of the following statements? a) 110 FOR N=1 TO 20 120 LET A(N)= N 130 NEXT N b) 110 DIM X(15) 120 READ X c) 110 DIM X(15) 120 LET K3 = 62 d) 100 DIM A(12) 110 LET A( 15) = 15 e) 100 DIM Z(k) f) 100 DIM A(4 000 000) 90 91 CHAPTER 9.0 THE TRANSFER OF CONTROL STATEMENTS 9. 1 GO TO 5TATEt-£ NT The GO TO statement transfers control unconditionally to a specified statement (single GO TO) or conditionally to one of a set of statement numbers, depending on the value of an expression (computed GO TO). A simple GO TO statement can have only one statement, and control is transferred to that statement unconditionally(#) (see Figure 9.1). GO TO # If tffit statement whose statement number is#) is a non-executable statement, such as MTA or REM, control is then passed to the first logically executable statement following the specified statement. 9.2 COMPUTED GO TO A computed QJ TO statement transfers control to the first, second, .•• , nth statement nlJTlber, if the truncated integer value of the expression is 1,2, •••. , N respectively, at the time of execution. GOTO 51, 52, •.•. 5N ON ARITHMETIC EXPRESSION where 51, 52, •.•. 5N are statement numbers. For example, if the value of the expression is 3.75, control will transfer to the third statement number in the list. If 10 LET X = 4. 7 5 20 Cll TO 30, 40, 50, 60 ON X-1 GO TO Statements Va 1 i d Invalid 10 GO TO 100 10 GO TO 3/2 20 GO TO A9 30 GO TO 11 10011 Fig. 9.1 ExaJlllles of valid and invalid ro TO statements. 92 93 then control will be passed to statement 50. If the value of the expression is less than one or greater than N (the number of statement numbers in the 1ist), control passes through to the next logically executable statement following the GO TO statement. If the statement branched to is non executable, again, control passes to the first executable statement following the specified statement. 9. 3 ON STATEMENT The ON statement causes multiple branches to take place in a program. The general format is given in Figure 9.2. ON \ the word ON A GO TO '-.r-J variable name the words GO TO 200, 15, 15, 490 ~ A list of line numbers (duplications are allowed) Fig. 9. 2 The genera 1 form of the ON statement. 94 Depending on the value of the variable name1the program will branch (jump) to statement 200 tA=l), 15 tA=2 or 3), 490 tA=4). For values 1ess than 1 or greater than the number of statements in the 1ist, an error message wi11 be generated. So!TE systems use the following format for the ON-G~ T~ statement: G~ T~ (Nl, N2, •.•. ) E where Nl, N2, . are the line numbers, and Eisa numerical expression or a variable. During the execution of this statement, the computer calculates the integral part of the va1ue far the ex press i on E. Note that some systems will not jump to statement numbers containing the statements MTA, DEF, DIM and REM. Examples of valid and invalid conditional GOT~ statements are given in Figure 9 .3. 9.4 lllE IF STATH£NT The IF statement tests a relational expression. If the relation is true, control is transferred to the specified statement number. If the relation is false, control is passed to the next logically executable statement. The general format is I IF X op Y THENJCl) TO statement # where X and Y are scaler expressions, 11 0p 11 is a relational operator, and THENIGO TO are interchangeable key words (either may be used, but not both, see Figure 9.4). Statement # is the number of the statement to which control is transferred if the ( expression is true. For example, 30 IF 40 IF 50 IF 60 IF A( 3) > X+2/Z Sl ~) 37.22 A+B B*C '-- . ., A condition to be tested The word THEN or the words GO TO lliEN 500 Where to go (branch to) if the condition is 11 true 11 • Fig. 9. 4 The genera 1 form of the IF statement. 96 97 The scaler express ions must both be either arithmetic or character expressions (character compared to a character, or arithmetic compared to arithmetic). A character constant containing 1ess than 18 characters will be padded with blanks on the right, while morethan 18 characters will be truncated on the right (again, i.mplementation dependent). If the statement branched to is a non-executable statememt (such as DATA or REM), control is transferred t~ the first logically executable statement following the specified statement . , The standard format for the IF statement is IF exp 1. op exp2 THEN n or IF expl op exp2 GO TO n where expl and exp2 are arithmetic expressions, op a relational operator, and (expl op exp2) a logical expression. The logical expression is evaluated, and if the relation is FALSE, then control passes to the next executable statement. On the other hand, if the relation holds (i.e., TRUE) then control is transferred to the statement at line number n. Examples of valid and invalid IF statements are given in Figure 9. 5. Other implementations of the IF statement that llil.Y be encountered include: ( 1) IF expl op exp2 THEN ( n1 , n2, . , nn), exp3 where (n 1, n2, . . nn) is an ordered list of line numbers, just as in a computed GO TO statement; expl, exp2, and exp3 are arithmetic expressions, op a relational operator, and (expl op exp2) a logical expression. Again, if the logical expression is False, control passes to the next executable statement. On the other hand, if the logical expression is True, then control is transferred to the statement in the list of line numbers depending on the value of exp 3. The truncated value of exp3 must be between 98 IF - Statements Va 1 i d I nv a 1 id 10 IF A>= 7 THEN 100 10 IF A 11=11 10 THEN 100 20 IF A1 > ((B+C/D)*(E+F) THEN 110 20 IF A$ = 10 THEN 110 30 IF 7· - M5 B$ THEN 200 Fig. 9.5 Examples of valid and invalid rF statements. 130 n1 and nn(i .e., the 1 ine numbers) or else execution is terminated. ( 2) I IF explop exp2 THEN: ES 99 where ES is a BASIC executable statement, and expl, op, and exp2 as above. If the logical expression is False, control passes to the next executable statement. If the 1ogical expression is True, then statement ES is executed. 9.5 EXCERCISES 1. ) Write a statement or group of statements to do each of the following. 2.) a) If a >b, set X= 16 . 9; but if a~ b then set X= 23.1. b) If a> s, set t=1; if a 4 THEN 300 d) 100 IF N= B THEN GO TO 30 g) 100 IF A$= YES THEN 45 h) 100 IF A=> B THEN 500 i) 100 IF A~B OR Abdi fi one or more values Jenninat ion Con d i t i on ( s ) met Fig. 10.1 General Loop Structure. 104 105 FOR A = 15 TO 100 STEP 3 f the word FOR the counter index the in it i a 1 v a 1 ue of the counter The value that the counter rray equal (but not exceed) For (variable) \ ntJTieric literal} = variable to expression NEXT A \ word NEXT Counter index (variable) The incremental step size lif not specified, assumed to be one) { numeric literal] ~numeric literal variable step variable expression expression Fig. 10.2 General form of 1oop structure and FOR statement. 1 06 At that time, the specified increment (X3) is subtracted from the value of the control variable, and control "falls through" to the first executable statement following the NEXT statement. A 1 oop can also be incremented negatively (i.e., decrerrented) by the correct specification of the initial value (Xl), the final value (X2), and the increment value [ (X3). If a loop is to be decremented, the initial value (Xl) must be larger than . the fi na 1 value tX2). The following are general rules that apply to the FOR-NEXT loop: [ ( 1) The value of the control variable (CV) may be modified by state~ nts within the loop, but its initial value (X1), final value (X2), and increment (X3), l are established during the initial execution of the FOR statement and are not affected by any statements within the FOR loop. (2) If the optional step expression is omitted in the FOR statement, the increment value is automatically set to -+1. (3) If the initial value (X1) assigned to the control variable is greater than (less than for negative increments) the final value (X2) when the FOR statement is evaluated, the loop is not executed and no value is assigned to the control variable (CV), and execution proceeds from the first executable [ statement fol1owing the associated NEXT statement. (4) If the step option is to be assigned a value which is contradictory to the r increment direction implied by the initial and final values (e.g., FOR X= 1 TW 5 STEP - 1), the FOR 1oop is not executed, no value is assigned to the control variable, and the execution proceeds from the first executable statement fa 11 owing the associated NEXT statement. (5) If the value of the step option (X3) is zero, the loop is executed an infinite number of times, or until the control variable is set outside of the specified region (greater than the final value, or in the case of negatively [ 107 incremented loops, less than the specified final value). ( 6) Transfer of control into or out of a FOR loop is permitted. However, a NEXlf statement may not be executed unless its corresponding FOR statement has been executed previously. (7) FOR loops may be nested within one another as long as the internal FOR loops fall entirely within the external FOR loop. Nested FOR loopsmray use the same control variable. (8) The maximum number of levels permitted when loops are nested varies among BASIC implementations. The first example shows a simple FOR loop: 20 FOR I = 1 TO 25 STEP 2 (Basic Statements) 95 NEXT I the control variable I is first initialized to 1, and the set of statements between the FOR and NEXT statements are executed once. Upon reaching statement 95~ I is incremented and compared with the final value of 25. If I is greater then 25, control is passed to the next executable statement following the NEXT statement. If I is less than or equa1 to 25, the increment of 2 is added to 1, and control is transferred back to the beginning of the loop. The next example shows the correct technique for nesting FOR loops. The inner loop is executed 100 times for each execution of th~ outer loop. 108 [ 10 FOR J = A T~ B STEP C + Z*2 (Basic Statements) 150 FOR K = 1 TO 100 {Basic Statements) 280 NEXT K 620 NEXT J Consider the following example: 10 FOR I = 10 TO 1 STEP - 6 40 NEXT I The loop will be executed twice. The first time through} I = 10. Upon executing the NEXT statement, I is decremented by - 6, hence I = 4. On the second pass through the loop, I is decremented by- 6, and again I=- 2, which is less than the specified final value of 1. Control then passes to the first executable statement following the NEXT I statement. Assurre a program is written as : 10 FOR I= 1 TO 40 STEP 2 40 LET I= I*2 l 50 NEXT I l 60 LET X - 4 I 109 If at statement 10, I = 6, then at statement 50, I is incremented to 14. The control variable I is modified by statement 40 and when statement 50 is reached, I= 12 and is then incremented by 2. Thus, I = 14. If at statement 10, I = 19, then at staterrent 50, I is incremented to 40, and control goes to statement 60. In the following program: 10 LET X= 10 20 IF A=B TiiEN 80 30 IF C=X THEN 100 40 FOR I = 1 TO X 80 FOR K=l TO 5 100 LET F= 100 150 NEXT K 160 NEXT I 170 LET G=200 If control was transferred fr001 statement 30 to statement 100, none of the FOR loops are initialized, and statements 120 and 160 will be ignored. If, on the other hand, control was transferred from statement 20 to 80, the K-loop is initialized and is executed the specified amount of times. Again, statement 160 is ignored because the !-loop had not been initialized. Examples of valid and invalid FOR statements are illustrated in Figure 10.3. 110 FOR Statement Va1id Invalid 10 FOR I = 3.5 TO 10 10 FOR K = 1 THRU 100 20 FOR J = 0 TO 10 STEP 1. 8 20 FOR AB = 10 TO 20 30 FOR K = -10 TO -3 30 FOR 3A = 10 TO 50 STEP -5 40 FOR L = -50 TO -100 STEP -2 40 FOR C = 25, 50 STEP • 5 50 FOR M = P*3 TO (C+D)/2 STEP 5*A 50 FOR s FROM 1 TO 50 Fig. 10.3 Examples of valid and invalid FOR statem:!nts. 10.1 EXCERCISES 1.) What is wrong with each of the following statements? a) 100 b) 100 110 FOR FOR LET A$ = 1 N = 1 T = T + N 120 PRINT T 130 END c) 100 FOR c = 1 110 c = 2 120 NEXT C d) 100 FOR .I = 1 110 READ V 120 GO TO 100 130 NEXT I e) 110 FOR K = 1 120 READ N 130 IF N > 10 140 NEXT K 150 LET C = C+1 160 NEXT K F) 100 FOR A = 5 110 LET D = D - A 120 NEXT A TO 50 TO 10 TO 100 TO 10 TO 5 THEN 150 TO 1 11 1 112 .g) 100 .FOR I = 1 TO .10 110 FOR K = 1 TO 5 120 LET N = I*K r 130 PRINT N ( 140 NEXT I 150 NEXT K [ h) 100 FOR N = 1 TO C$ [ i ) 100 FOR I = 1 TO 10 l 110 PRINT I, I • 2 120 END l j) 100 FOR A = 1 TO 5 STEP 1 110 LET T = T + A 120 GO TO 100 130 NEXT A k) 100 IF X = 1 OR 5 THEN 60 1 ) 100 FOR A = -100 TO 0 STEP + 1 r 2.) What is wrong with each of the following statements? [ a) 100 FOR K = 1 THRU 10 ~ b) 100 FOR PO = 10 TO 99 c) 100 FOR 3X = 100 TO 140 STEP -5 [ d) 100 FOR A = 25, 35 STEP .5 t e) 100 FOR A FROM 5 TO 25 f) 100 FOR AS = 1 TO 5 STEP g) 100 FOR A(5)= 1 TO 5 ~) 100 i) 100 j) 100 FOR FOR FOR A = 1 A3 = 0 TO TO -10 100 STEP . 05 A = B(1) TO B(2) STEP B(3) 3.) Which of the following FOR and NEXT loop nests are valid? (a) [ (e) (b) (f) [ [ [ (c) [ [ (g) (d) (h) 113 4.) What is printed by eacn of the following programs? a) 100 110 120 130 140 FOR I = 1 TO 3 READ A$, R PRINT A$, R NEXT I DATA CAT, 123, DOG, 456, HAT, 789 150 END b) 100 DATA 11 DAY 11 110 DATA 1,2,3 120 READ A$, I , J' K 130 PRINT A$, I 140 PRINT A$, J 150 PRINT A$, K 160 END 114 115 CHAPTER 11.0 SUBROUTINES A subroutine is essentially an independent program, but it is written in such a way that it can be executed only when called by another program. Subroutines, like functions, are used to perform tasks that are needed on Jll)re than one occasion. A subroutine call can be written at any place in a program. That is, at different times and/or in different locations, a main program may call upon a subroutine to perform a certain opera.t. ion. A subroutine may be called any number of times, and reentr_v to the main program at the proper point is automatically controlled by the calling statement. Subroutines offer a powerful means for accomplishing a very basic task in programming; the process of using the same set of statements repeatedly. 11.1 THE ~SUB AND RE11JRN STATEMENTS The GOSUB statement transfers control to a specified statement. The RETURN statement transfers control to the first executable statement following the last ~SUB statement executed. TogetherG$SUB and RETURN statements are used in the creation of subroutines . The general format of the GOSUB and RETURN statements are: G~SLB NNNN RE11JRN where NNNN represents the number of the statement to which contra 1 is to be transferred ( s ee F i gu re 11. 1 } . Execution of a ~SUB statement causes an unconditional transfer of control to the statement whose number is specified. If the specified statement is non-executable, control is passed to the first executable statement following the 1ast GQSUB statement executed. GOSUB 2000 i the wo rei GO SUB A 1ine number Fig. 11.1 The general form of the GOSUB statement. 116 11 7 ' The genera 1 ru 1 es that apply to the G~S lE and RETURN statement fo 11 ow : • I ( 1) M::>re than one G~SlE statement may be executed before a RETURN statement is executed, but when a RETURN statement is executed, there must be at least one a) suB statement already executed for which a corresponding RETURN statement has not been executed. (2) The maximum number of levels permitted when subroutines are nested) varies among BASIC language implementations. The following examples illustrate the fiVSUB and RETURN statements. In this example, statement 50 transfers control to statement 100, and then upon reaching statement 140, control is transferred back to the next executable statement following the ~SUB statement {in this case, statement 60). In the next examples 50 GOStE 100 60 LET X = 1 100 LET X = A+B 140 RETURN 80 ffiSUB 150 90 LET X = 1 150 LET A$ = 190 GOSlE 250 200 240 RETURN I CAT' . 250 LET y = X+Z 300 RETURN 118 Control is transferred frCJTl statement 80 to statement 150. The program then continues from staterrent 150 until it reaches statement 190. At this point, control is trans- referred to statement 250, and the program continues. When processing reaches statement 300, control is passed back to the next executable statement following the last GOSIJ3 statement that was executed last. Thus, in this case, control is transferred back to staterrent 200. Processing continues from statement 200 until it reaches statement 240. Again, [ cantro1 is transferred back to the executable statement fall owing the GO SUB statement. In this case, control is now transferred back to statement 30. In the following example: 10 LET X = K 20 GOSUB 400 30 LET A = B 40 GOSUB 410 50 REM THIS IS A COMMENT 60 LET X =At£ 400 LET C = 0 410 LET B = C 420 RETURN When staterrent 20 is executed, control is passed frCJTl statement 20 to 400. statement 420 is encountered, control is transferred back to statement 30. When After statement 40 is executed, control goes from 40 to 410, and then from 420 back to staterrent 60 (statement 50 is a non-executable statement). It is important to realize that the computer will exit from a subroutine only by a RETURN statement, and not by a GO TO, IF-THEN, or ON-GO-TO statement. 11. 2 REMARKS The REM statement (e.g., statement 50) allows the user to insert comments into the program 1 i sting. The general format is: 11 9 REM (COMr-I:NT) where comment is one or more characters. The COMMENT may be omitted (see Figure 11.2):. The REM statement is non-executable and has no effect on program execution. Furthermore, it may appear anywhere in the program. Some BASIC implementations allow appending remarks to BASIC statements by having the BASIC statement followed by I * 11 Comments 11 .- Examples of valid and invalid remarks are shown in Figure 11.3. documentation or comments \ --- REM T the word REM Comments of any desired form Fig. 11.2 The general format of the REM statement. 1 20 121 REMARKS Valid 20 REM *** THIS IS A FUNCTION *** 30 REMARK - THE MAIN CALCULATIONS FOLLOW Inva 1 i d 20 *** PROGRAM TO INVERT MATRIX *** 30 *REM * BASIC PROGRAM - INVERSE * Fig. 11.3 Examples of valid and invalid remark statements. [ 11.1 EXCERCISES 1.) What is wrong with each of the following statements? a) 150 250 260 b) 100 200 GO TO 250 READ A,B,C RETURN GO SUB 200 PRINT A,B 300 END c) 100 110 200 d) 100 110 240 GO SUB 110 READ N,M RETURN IF A = 20 K = K+l READ X,Y 260 RETURN THEN 240 122 e) 100 READ A 110 GO SUB 200 120 PRINT A 130 GO TO 100 200 LET A = A*4 210 END f) 110 READ A 120 GO SUB 150 130 PRINT J, A 140 IF J "10 THEN 110 150 LET J =J+1 160 RETURN 170 END 2.) What is printed by each of the following programs? a) 100 FOR I = 1 TO 6 110 LET N(I) = I 120 NEXT I 130 PRINT N(3), N(4), N(5) 140 END b) 100 DHi X(3), Y(3) 110 DATA 1,2,3,4,5,6 120 FOR I = 1 TO 3 130 READ X(I), Y(I) 140 NEXT I 150 FOR L = 1 TO 3 123 160 PRINT Y(L), X(L) 170 NEXT L 180 END c) 100 FOR I = 1 TO 5 110 GO TO SUB 140 120 NEXT I 130 STOP 140 PRINT I; 150 RETURN 160 END 124 126 CHAPTER 12.0 THE STOP AND END STATEMENTS The S1DP statement causes program execution to be terminated. The general format is STOP (COt>t1ENT) where COMt>l:NT is one or more characters. The ccxnment may be omitted. A STOP statement can serve the same purpose as GO TO XXX, where XXX is the line number of an END statement. The STOP statement is different fran the END statement in that it has no effect on the compilation (translation) of the program. The STOP statement may appear anywhere in the program. E.g., 80 IF X 0 THEN 100 90 STOP 100 PRINT X The END statement causes the termination both of the compilation (translation) and of the execution of the BASIC program. It has the following format: GJ where optionally a comment of one or 100re characters may follow the word END. E.g., END THIS PORTION OF THE STATEMENT IS A COMMENT The END statement indicates the logica1 end of a program. When it is encountered during program translation, it causes any statements which follow it numerically to be excluded from the program .When an END statement is encountered at execution time it causes termination of processing and closing of all open files. The END statement 127 [ is optional. If omitted by the programmer, END will be assigned by the system to follow the highest-numbered statement in the program. Examples of valid and invalid statements are shown in Figure 12.1. STOP and END Statements Valid 500 STOP 10 600 END END Fig. 12.1 Examples of STOP and END. 128 Invalid I IF B ., 100 THEN STOP CHAPTER 13.0 FUNCTIONS 129 Sometimes in programming it may be necessary to compute the same mathermtica1 routine using many data values during the program. Rather than writing the same calculations every time, the function capability of BASIC may be used. 13. 1 FUNCTION, ARGUf.I:NT AND REFERENCE A BASIC function is a named arithmetic expression that computes a single value from another expression. For example, the SIN function computes the sine of any l number of radians. The value in parentheses following the name of a function is called its argument. I In the function reference SINt5), 5 is considered to be the argument. It is rarely an arithmetic expression representing a value that the function is to act on. A function reference is the function narre with its argument. The expression SIN (5) is called a function reference. It computes the sine of five radians. Likewise, the function reference SIN(X) represents the sine of the number of radians equal to the value of the variable X. A function reference may be used anywhere in a BASIC expression where a constant, variable, or array member reference may be used. The foll o.-Jing are sorre examples: LET A= SIN (8.32) + 1 LET B = SQR (X + 3) LET C = INT (Y*(X + 3)) + Z**2 13.2 BUILT-IN OR INTRINSIC FUNCTIONS BASIC pro vi des functions that perform a number of common rra thema ti ca 1 operations. These may be called intrinsic or built-in functions. BASIC also allows the programlll2r ( to define and na!ll2 frequently used functions through the use of the DEF statement . The following is a 1ist of BASIC functions. The items with a star(*) are those functions l 130 provided by just about every BASIC system. the implementation of the language in use. The others may not exist, depending on Tables 13.1 to 13o3 provide a list of these built-in functions. Examples of valid and invalid uses of built-in functions are given in Figure 13.1. Please note: (1) Each ·time RND is called with an argument, the random number generator is initialized to the value of that argument. Subsequent references to RND without using an argument will cause the new number to be generated ·from the previous one. If RND is called without an argument and there has been no previous initialization, the generator will initialize itself. (2) Exponentiation operations and some intrinsic function computations are performed by proven mathematical approximations. Occasionally, results may The t 1) be inaccurate in the least significant positions because of the limitations of the approximation methods. One way to overcome this problem is to print fewer significant digits, or to use the long-form arithmetic (if the implementation allows this form of arithmetic). Probably a cQmbination of the two will result in the most satisfactory answer. following are some typical examples in the use of i ntri ns ic functions: BASIC Statements Inter~reta ti on 20 LET A=S IN (B) A = Sine of B 30 LET X=LOG (T+V) X = log base e of (T+V) 40 LET S=SQR (COS(T)) s = square root of cosine T (2) The RND function is a special BASIC function which gives a different randan ( number between 0 and 1 each time that function is called in a program. Table 13.1 BASIC built-in Functions. Function *ABS( X) ACS (X) AS N (X) *ATN( X) *COS( X) COT (X) esc ( x) DEG (X) DE T (X) *EXP (X) HCS (X) HSN (X) HTN (X) *I NT( X) LGT (X) *LOG(X) L TW (X) RAD (X) *RND(X) SEC (X) *SGN( X) *SIN( X) *SQR( X) *TAN( X) Defin it ion Ab so 1 u te va 1 u e o f X Arc-cosine (in radians) of X Arc-sine (in radians) of X Arc-tangent (in radians) of X Cosine of X radians Cotangent of X radians Cosecant of X radians 1 31 Number of degrees in X radians Determinant of an arithmetic array X (X must be a square array) Natural exponent of X Hyperbolic cosine of X radians Hyperbolic sine of X radians Hyperbolic tangent of X radians Integer part of X Logaritlln of X to the base 10 Logarithn of X to the base 11 e 11 Logarithn of X to the base 2 Number of radians in X degrees Random number between 0-1 Secant of X radians S i gn of X ( -1 , 0 , o r + 1 ) Sine of X radians Square root of X Tangent of X radians 132 [ Table 13.2 BASIC Trigonorretric Functions Narre Content A rg l.ITlen t Result Exafll) 1 e ACS Angle in radians whose nurreri c angle in ACS(. 54) trigonanetric cosine is express ion radians the argurrent (arcosine) ASN Angle in radians whose numeric angle in ASN(.67) tri gonorretric sine is express ion radians the argl.ITlent (arcsine) ATN Angle in radians whose numeric angle in ATN(3.2} trigonometric tangent is expression radians the argument (arctangent) cos Cosine of argument in n lJller i c numeric COS( 6. 4) radians expression constant HTN Hyperbo 1 i c tangent of nLITler ic numeric HTN(.20) argument in radians expression constant SIN Sine of argument in numeric numeric SIN(3.14) radians expression constant TAN Tangent of argument numeric numeric TAN (1. 5) in radians expression constant [ Table 13.3 BASIC Noustring Functions Name Content Argument ABS Absolute va1ue of an numeric a rg lJTl en t . express ion EXP e(2.7183) raised numeric to a power (the argu- expression ment). INT truncates the result nlJTler ic of the argument. expression LGT common log of a numeric or CLG positive argument express ion (base 10) LOG natural log of a numeric positive argument expression (base e) RND generates a random simple number numeric variable SGN sign of argument n Lmler ic arg. < 0, sign -1 expression =-0, sign 0 >o, sign 1 SQR square root value numeric value of positive expression a rg LJTlen t Result positive constant numeric constant integer constant numeric constant numeric constant numeric constant -l,O,or + 1 numeric constant 1 33 Example ABS(A*B) EXP(5.1) INT(17. 3) LGT(A*B) LOG(10) RND(K) SGN (X) SQR(A+4) Built-in Functions Va 1 i d 10 LET A= SIN(B) 10 20 LET B = EXP(SQR(B*B)) 20 30 LET c = LOG( D+E) 30 35 LET D = SQR(COS(T)) 40 40 LET E = SQR (D t 3 + SQR( F) ) 50 50 PRINT TAB (1); A, 8, TAB(10*SIN(OJ}; 11 *11 Fig. 13.1 Examples of valid and invalid uses of built-in functions. 134 Invalid READ ABStA) LET B = SQR LET SQR(X) = 16 PRINT SQRT(INT() ) LET A$ = INT(SA) 3990 LET X = 13 40 00 LET Z = R NO ( X ) 4010 PRINT Z 4020 GO TO 4000 9999 END 1 35 The above program shows an endless loop during which random number after random nl.ITlber is requested. By actual test, thousands upon thousands of random numbers can be obtained without ever repeating a number. At the termina1, the above program could easily be terminated. As a batch job (submitted on cards) the loop 'J soould be ended by means of a counter. Otherwise, the loop will continue until the time 1imit or the 1ine print 1imit is reached. 13.3 EXAMPLE FUNCTIONS 13.3.1 Integer Function The INTEGER function, INT{X), returns a value equal to the greatest integer not larger than X. For example, if X is 3, INT(X) is 3. If X is 1.7, INT(X) is 1. If X i s - 2 . 2 t he n I NT ( X ) i s - 3 . INT(X) can therefore be used to determine if a number is an integer. This would happen when INT(X) is equal to X. To round numbers, add 0.5 to it, and then take the integer INT of the sl.ITl. A program that uses these concepts is given below 10 LET A = 2.8 20 LET B = A + 0.5 30 LET C = -A 40 LET D = C + 0. 5 50 PRINT A,B,C,D 60 PRINT I NT (A) , IN T ( B ) , I NT( C ) , INT( D) 70 END The output of this program is 13.3.2 Sign Function 2.8 2 3.3 3 136 -2.8 -2.4 -3 -3 The Sign function SGN(X) returns a value that tells whether a number is positive, negative, or zero. If X is positive, SGNtX) = + 1 If X is zero, SGN(X) = 0 If X is negative, SGN(X) = -1 An exaJll>le program for finding the sign of variables is as follows: 10 LET X = 42 20 LET y - 10 30 LET -rz = -5 40 LET A = X - (Y*Z) 50 LET B = ( Y+Z) * 0 60 LET C = X/Y * Z 70 PRINT A; SGN(A) 80 PRINT B; SGN(B) 90 PRINT C; S GN (C) 100 END The output of this program is 92 1 0 0 -21 -1 1 37 13.3.3 Absolute Value Function To determine the value of a number without regard to its sign, the absolute value function, ABS(X) returns the positive value of X. An example of such a program is 10 LET A = 400 20 LET B = - 75 30 PRINTA,-·B 40 PRINT ABS(A), ABS(B) 50 END with the fo11owing output 400 - 75 400 75 13 .4 EXCERCISES 1.) What are the values of each of the following: 2. ) ABS (-13.2) ABS 13. 2) INT 16.3) INT 16.9) INT (-16.3) INT (-16.9) RND (X) 10 * RND(X) INT (10 * RND (X)) INT (15 * RND (X)+5) INT (A * RND (X)+B) INT (-.0001) INT (-7.5+.5) What does the following program do? 100 DEF FNA(I) = INT (I * RND(0)+1) 110 FOR I = 1 TO 100 120 PRINT FNA ( 3) 130 NEXT I 140 END 138 3.) 4. ) 5.) Check the accuracy of the various functions in BASIC by computing: Sin2 (x) + Cos2 (x)-1 ( rx )2 - x from 0 to 2 in 0.1 from 0 to 1 in 0.05 e 1 og X -. X from 0 to 10 in 1. Some functions are in BASIC only for convenience. They could be replaced by subroutines. Write subroutines to define ABS, SGN and INT. Define functions to correspond to each of the following equations. x2 + y3 + XY Sin X + cos2 X Sinh X = 1/2 (eX- e-X) Cosh X = 1/2 (eX + e-X) r = d * (3.14159265/180) ~ x2 + Y2 + z2 X log 10 (X2 - a2) ( e{X+2 )cos (3X + 1) 6.) Write a program which asks for two numbers Nand P, and then rounds off N to P places. Use a function to round off N. 139 140 7.) Write a program which defines a function fO(), and then find one ordered pair (X, f(X)) for which the graph ofF has a maximum or a minimum value in some interval A 6 X: B. 8.) Using only the addition, subtraction, exponentiation, and comparison operations, calculate and print the square root of 103 to the nearest one-thousandth. 9.) Write a program that uses the functions SIN and COS to compute Sin2 X+ Cos2 X= 1 for X = 0 to 100 in increments of 0. 3. In order to examine the accuracy of the built-in functions, compute the percentage error for each computation. C = Sin2 X + Cos2 X using p.e. = 100 * li-G.I= 100 \ 1- c \ 1 10.) What is the output for this program? a) 10 DEF FNS(X) = X*Y + (1-X) * Z 20 READ y' z, w 30 s = 0 40 FOR I = 0 TO 1 50 s = S+ (FNS(I))t 2 60 NEXT I 70 PRINT S/W 80 DATA 3,4,5 90 END b) 10 20 30 40 50 60 70 80 90 100 110 120 130 FOR I = 1 GO TO I OF GO SUB 80 GO SUB 60 GO TO 90 GO SUB 100 NEXT I STOP PRINT "A" PRINT 11 B" PRINT "C" RETURN END TO 3 30 ,4(l, 50 141 142 CHAPTER 14.0 PROGRAMMING GUIDELINES AND DEBUGGING We know from practical experience that some programs are well~ritten, and we call these 11 good 11 programs. In the past, the quality of a program was essentially a matter of value judgement which varied from person to person. Over a number of years, however, a consensus seems to have emerged in the programming conmunity about a set of criteria to be used to ascertain the 11 goodness 11 of a program. In this chapter we discuss these criteria and make suggestions for writing good programs. 14.1 CRITERik OF GOODNESS In judging the quality of a program, we can use various ccxnbinations of the following measures: Simplicity: In order to understand the flow of control in a program during execution (i.e., what is really going on when the program is running?) and to debug, it is essential that the program be written in a simple, straightforward manner. By Sifllllicity we mean logical clarity: avoidance of too many haphazard branches and of clever pieces of code which hide their purpose, etc. Reliability: It is the job of a programmer to convince the user of a program that the program actually does what it claims to do. The only foolproof way of achieving this goal is to prove a program to be correct by mathematical logic. However, for complex programs this is exceedingly difficult to do, and unless automatic program proving systems capable of handling complex programs are designed in the fut u~e, this approach wi11 not be very useful. The only alternative available to a programmer to convince a user of a program's value is to explain the organization of the program and the tests used. If the user realizes the careful thinking that has gone into the organization and testing of a program, he/she may be persuaded to trust the program output. 143 Adaptability : The processing requirements of a program often undergo gradual but significant changes over a period of time. For example, in a program that simulates r a simple queue, it may become necessary to add more than one server and/or more than one priority of service over a period of time. The simple simulation model should be written so that it can be easily modified to incorporate such changes. Programs r which can easily be modified to satisfy new requirements are called adaptable. Highly efficient programs can be written by clever coding, but such programs are often complex, of unknown reliability, and difficult to modify. Portability: A program is portable when it can be transferred from one computer system to another with very few changes or no changes at all. Clearly, portability will make a program more cost-effective and can be attained with programs written in standard source languages. 14.2 GENERAL GUIDELINES FOR PROGRAMMING Simplicity appears to be the key in writing good programs. If a program is unnecessarily co!llJlex due to jX)Or organization, it will be difficult to test. This in turn will prevent users from ascertaining its reliability, even in a subjective manner. It is difficult to adapt a complex program to changes in requirements, and there is not much rootivation for transporting a complex program of unknown quality from one sys tern to a nether. Only gains in efficiency can sometimes be attained by using complex code. One way to avoid unnecessary complexity in a program is to start with a complete [ picture of the overall requirements for the program. If all the requirements have not been specified, this should alert the programmer about possible adaptations that l may be needed later on. In any case, an attempt to create such a 1ist of requirements usually clears up any misunderstandings a programmer may have about a user's requirements. For example, before designing a simulation program, the programmer should determine {i) whether the system to be simulated is discrete-time or continuous-tirre, or both, and ( ii) in case of discrete-tirre systems, whether they are event-·driven or 144 use fixed-time increments. When at least the major requirements of a program are known, the programmer should design the tollf!OSt level as a functional module. Starting at this level, the programmer should always search for different methods to implement his/her idea s'9 always opting for the simplest approach unless grossly inefficient. Trade-offs must be na.de between simplicity and efficiency, and only experience can teach one how to choose among alternatives. The top-level functional module should be decomposed into submodules fanning the lo~r levels. The function and interface of each module should be carefully and completely described. Before any cadi ng is started, the programmer should give some thought to the data structures in the programs since a poor choice of data structures often complicates program logic. For simplicity, each module can be conceived as a subprogram although it is not strictly necessary to implement it in that way. Simple subprograms are more efficiently implemented as integral parts of the calling program. Testing should be na.de an integral part of program development and not left until the end . 14.3 DEBUGGING One of the most important tasks facing a new programmer is learning to debug a program successfully. Few people are able to write a program and to have it run correctly the first time. In fact it is not unusual to spend as much time testing and debugging a program as writing the program initially. To debug successfully requires the development of new skills to supplement the programming skills of the individual. By following certain predefined steps, a program may be debugged and made to work in the way that the programmer originally intended. The major debugging and testing considerations that we will discuss are: (1) Desk Checking (2) Syntax and Semantic Errors [ (3) Tracing Program Logic 145 Generally, testing proceeds in this order, but changes to the program at any time can cause the prograJTTller to go back to any of the earlier steps. This may be the result of errors that were overlooked previously or because of new errors that were introduced during the testing process. 14.3.1 Desk Checking This is probably the easiest of all debugging techniques and yet the most often overlooked. After careful planning and flo~harting of the solution, the programmer will write the BASIC code. Coding the program should be done on paper, not at the terminal or keypunch. Use of block lettering, not writing, will reduce errors made when the program is keypunched or keyed into a data entry device. At this point, take [ some time to desk check the code. If the program was keypunched, examine the cards [ (hopefully they were interpreted); if a tenninal was used, read the printout. It is surprising how many errors can be detected at this stage without the computer’s assistance. Types of errors to look for at this stage are spelling errors, keying errors, missing or duplicate statements, and statements out of order. 14. 3. 2 Syntax and Semantic Errors This step is concerned with using the language correctly, as it is defined for a specific machine. Since each BASIC interpreter or compiler is unique in some ways, we will not attempt to discuss all types of errors but rather to provide some guidance for their correct1on. Syntax refers to improper punctuation of statements in the language) whereas semantics refers to the proper understanding of the statement format. This is generally discussed throughout the book, so a detailed presentation will not be given here. Syntax errors are many and varied. In a number of cases, it is difficult to determine whether an error is in the syntax or the semantics of a language. Although there are precise definitions of these, we are more concerned with finding the errors. 146 The following is a list of errors that are encountered quite frequently by programmers. fvbst of these errors are identified by error messages from the translator . A 1ist of these messages may be found in Appendix VII. Type of Error Missing Ccxnmas Parentheses Opera tor Mismatch Il 1 ega 1 Verb Arguments Do Not f'la tc h •Example 10 N(1 K) = A+B 10 INPUT A B Expl an at ion The co11111a separating subscripts 1 and K is missing. Two variables in input and output state· ments must be separated by ccxnmas. Some translators treai this as variable AB rather than an error. 10 N=N + 1)*5 Either too few brackets as in 20 A:r::(K + l*S+(J/N))) statement 10 or too many ~s in 20 can be the cause of th1s 10 N+N=K 20 J=B( N+L) 30 K=P* /J 10A$=10 20 N="DON SMITH " problem. Make sure that a 11 brackets are matching pairs. In line 10, the statement is reversed; this is a comrron problem with new progranmers. State ment 20 has the multiply operate missing after the B; some systen ca 11 this an error while others consider B to be an array and (N+L) the subscript. Statement 30 has two operators together; a variable is probably missing. This occurs when a numeric value is assigned to an alphanumeric variable or vice versa. 10 S=SQRT(256) This happens when a keyword is misspelled. SQRT is valid in some languages but not in BASIC. 10 DEF FNA(K,J)= K~ 2+Jt 3 50 PRINT FNA(16) This error occurs when two or more arguments are possible in a function. In this case, function A uses two arguments, but the call in statement 50 supplies only one. During program execution, errors, which are not indicated earlier, may be found. These are generally self-explanatory errors, such as dividing by zero, trying to calculate the square root of a negative number, and having arithmetic overflows or subscrip out of range. 14.3.3 Tracing Tracing is the process of following the program logic step error. This can be done manually for relatively easy problems, 147 by step to locate an or program statements can be used to show the flow of the logic. The key is to know what to expect from your program. If you know what output the program is intended to produce, then when it does not produce this output, a trace can be used to determine why. Manual Tracing This is done with a copy of the progran listing, its output (if any) and a pencil.This method is particularly useful for small; http://uab.contentdm.oclc.org/cdm/ref/collection/uab_ece/id/57

  4. 4

    Zdroj: Foundations of Digital Signal Processing: theory, algorithms and hardware design ISBN: 9780852964316

    Predmety: 4. Education

    Prístupová URL adresa: https://digital-library.theiet.org/content/books/10.1049/pbcs015e_ch3

  5. 5
  6. 6
  7. 7
  8. 8
  9. 9

    Alternate Title: Borun Biyolojik Koruyucu Etkileri Üzerine Küresel Araştırma Eğilimleri ve Tematik Gelişmeler: Kapsamlı Bir Bibliyometrik Analiz (1990-2025).

    Autori: Aşkın TEKİN1 askin.tekin@giresun.edu.tr

    Zdroj: Journal of Anatolian Environmental & Animal Science. 2025, Vol. 10 Issue 6, p844-860. 17p.

    Plný text ve formátu PDF
  10. 10
  11. 11

    Zdroj: Revista de Investigación; Vol. 11 No. 1 (2018); 113-125 ; Revista de Investigación; Vol. 11 Núm. 1 (2018); 113-125 ; 2590-6062 ; 2011-639X

    Popis súboru: application/pdf

    Relation: https://revistas.uamerica.edu.co/index.php/rinv/article/view/183/181; Ausubel, D. (2012). The acquisition and retention of knowledge. New York, EE. UU.: Springer.; Bruner, J. (2009). Actos de Significado. Madrid, España: Alianza Editorial.; Chukaew, S., Panjaburee, P., Wanichsan, D., y Laosinchai, P. (2014). A personalized e-learning environment to promote students conceptual learning on basic computer programming. Procedia-Social and Behavioral Sciences, 116, 815-819.; Evans, D. (2011). Introduction to computing. Charlottesville, EE. UU.: Computing Book.; Havenge, M., Breed, B., y Mentz, E. (2013). Metacognitive and problem solving skills to promote self directed learning in computer programming. SA-eDUC Journal, 10(2), 11-25.; Herrmann, W. (2015). The whole brain bussiness book. New York, EE. UU.: McGraw Hill.; Law, K., y Lee, V. (2010). Learning motivation in e-Learning facilitated learning computer courses. Computers & Education, 55, 218-228.; Saito, D., y Yamaura, T. (2013). A new approach to programming language education for beginners. En M. Lee (Ed.), IEEE International Conference on Teaching, Assessment and Learning for Engineering (TALE) (pp. 252-755). Kuta, Indonesia: IEEE.; Serrano-Cámara , L., Paredes-Velasco, M., Alcover, C., y Velazquez-Iturbide, J. Á. (2014). An evaluation of students motivation in computer supported collaborative learning of programming concepts. Computers in Human Behavior, 31, 499-508.; Tlili, A., Essalmi, F., Jemni, M., y Chen, N.(2016). Role of personality in computer based learning. Computer in Human Behavior, 64, 805-813.; Trejos, O. (2000). La esencia de la lógica de programación. Pereira, Colombia: Centro Editorial Universidad de Caldas.; Trejos, O. (2012). Significado y Competencias. Pereira, Colombia: Editorial Papiro.; Van Roy, P., y Haridi, S. (2004). Concepts, techniques, and models of computer programming. Boston, EE. UU.: MIT Press.; https://revistas.uamerica.edu.co/index.php/rinv/article/view/183

  12. 12
  13. 13
  14. 14

    Zdroj: Scientific Papers: Animal Science & Biotechnologies / Lucrari Stiintifice: Zootehnie si Biotehnologii. 2024, Vol. 57 Issue 1, p1-36. 36p.

    Plný text ve formátu PDF
  15. 15

    Autori: Schultz, Jörg1 (AUTHOR) Joerg.Schultz@Tier-Wohl-Team.de

    Zdroj: Frontiers in Veterinary Science. 2025, p1-16. 16p.

    Plný text vo formáte HTML Plný text ve formátu PDF
  16. 16
  17. 17
  18. 18

    Zdroj: Laskov, Lasko M. (2020) Practical Java: Learning in exercises. Manual. Научен електронен архив на НБУ, София. (Unpublished)

    Popis súboru: application/pdf

    Prístupová URL adresa: http://eprints.nbu.bg/3422/

  19. 19
  20. 20