$ BASIC [Return]
VAX BASIC V3.4
Ready
In order to introduce BASIC commands this manual assumes that you know the rudiments of the BASIC programming language (see "Programming in BASIC").
BASIC uses two kinds of memory on the VAX:
Internal Storage * temporary in nature (cleared when you exit the BASIC environment)
* where all BASIC programs are first created
* where a BASIC program must reside in order for changes or additions to be made
Disk Storage * permanent in nature (it will still be there tomorrow, and the day after, and ...)
* where BASIC programs (and all other files in your account) are permanently stored.
Ready
NEW TEST [Return]
Ready
If you do not supply a name BASIC will ask you for one:
Ready
NEW [Return]
New file name--TEST [Return]
Ready
Basic is ready for you to work on a program called TEST. You can now enter the lines of the program. You will not receive a BASIC Ready prompt after each program line. (We will no longer tell you to hit [RETURN] after each line).
10 PRINT "INPUT YOUR NAME";
20 INPUT NAME$
30 PRINT "HI THERE "; NAME$
40 END
Note: if you neglect to use the NEW command and simply enter a program, BASIC will use the default name NONAME.
LIST [Return]
TEST 1-FEB-1991 12:15
10 PRINT "INPUT YOUR NAME";
20 INPUT NAME$
30 PRINT "HI THERE "; NAME$
40 END
Ready
You can limit the amount that is printed by the LIST command by specifying a range of BASIC line numbers. Although this may not be necessary for a short program, in fact it can provide a more efficient method of viewing particular segments of a long program.
LIST 20-30 [Return]
TEST 1-FEB-1991 12:15
20 INPUT NAME$
30 PRINT "HI THERE "; NAME$
Ready
You can print lines starting at a specific line number to the last line by leaving out the second number. For example:
LIST 30- [Return]
TEST 1-FEB-1991 12:15
30 PRINT "HI THERE "; NAME$
40 END
Ready
RUN [Return]
TEST 1-FEB-1991 12:16
INPUT YOUR NAME? JOHN DOE [Return]
HI THERE JOHN DOE
Ready
It is possible for you to RUN a program that contains neither errors nor an end. If you encounter a situation where a program will not terminate (contains an infinite loop) you can stop it with [[Ctrl) C) (see "The Terminal Keyboard" in Introduction to VAX/VMS).
To SAVE the program called TEST simply type the SAVE command. BASIC informs you, with a rather cryptic message, that it saved TEST on disk and gave it the filename TEST.BAS;1 (see "Complete File Specification" in Introduction to VAX/VMS). Each time a file is saved it is stored on disk with the same name and extension but with a sequentially higher version number. For more information on these messages see "Debugging Example" in the Program Debugging section of BASIC.
SAVE [Return]
%BASIC-I-FILEWRITE, TEST written to a file:
MEENA4:[UNDERGRAD.DOE1234J]TEST.BAS;1
Ready
To SAVE the program called TEST under a different name, enter the SAVE command and supply another name:
SAVE HELLO [Return]
%BASIC-I-FILEWRITE, TEST written to a file:
MEENA4:[UNDERGRAD.DOE1234J]HELLO.BAS;1
Ready
SAVE does not affect the program in internal storage. Always remember to SAVE your work before you EXIT BASIC. Any work that you do not SAVE is gone forever.
OLD HELLO [Return]
Ready
Resequence makes the first statement of your program line 100 and increments by 10 for each other line.
LIST [RETURN]
TOOCLOSE 1-FEB-1991 12:20
10 REM Help!
12 REM There are no more line numbers
17 REM and I want to add more statements.
18 PRINT "HI"
19 END
Ready
RESEQUENCE [RETURN]
Ready
LIST [RETURN]
TOOCLOSE 1-FEB-1991 12:20
100 REM Help!
110 REM There are no more line numbers
120 REM and I want to add more statements.
130 PRINT "HI"
140 END
Ready
A BASIC program which contains syntax errors cannot be resequenced.
Automatic line numbers start at 100 and increase by increments of 10. The following procedure is used to sequence a BASIC program STUFF starting at 100 with increments of 10:
NEW STUFF [RETURN]
Ready
SEQUENCE [RETURN]
100 PRINT "This is a quicker way"
110 PRINT "to enter a program and is useful"
120 PRINT "when you have the whole program "
130 PRINT "on paper and ready to type"
140 END
150 [[Ctrl] Z]
Ready
The line number on which [[Ctrl] Z] is performed will not appear in the BASIC program.
Although sequence will automatically generate line numbers starting at 100, you can however, specify the starting number for sequencing and for the incremental value. For example:
Ready
SEQUENCE 200, 50
This will automatically sequence your program starting at 200 and increment the line numbers by 50 ; 200, 250, 300, etc..
To add a statement:
Choose a line number that does not currently exist and that will place the statement in the correct position in the program when the line numbers are sorted. Type the number and the statement.
To change a statement:
Retype the complete statement with the same line number as before. When you press[Return] the old one will be replaced by the new.
To delete a statement:
Type the line number of the statement and press [Return].
Note: A common pitfall is to enter a line number with an O (oh) instead of a 0 (zero). These are fairly easy to find as the line number 1O (one oh) will show up as the first line of a list command since it is line 1 with the first character of the statement being an O (oh) and not line 10 (one zero).
OLD TEST [Return]
Ready
LIST [Return]
TEST 1-FEB-1991 12:22
10 PRINT "INPUT YOUR NAME";
20 INPUT NAME$
30 PRINT "HI THERE "; NAME$
40 END
Ready
DELETE 20-30 [Return]
Ready
LIST [Return]
TEST 1-FEB-1991 12:22
10 PRINT "INPUT YOUR NAME";
40 END
Ready
EDIT line-number /old string/new string/ [Return]
Where:
line-number * is the number of the statement that you want to change
old string * is a string of characters in the statement that you want to replace
* must be contained within slashes
* must exactly match what currently exists in the line; uppercase and lowercase letters must correspond.
new string * is a string of characters that you would like instead of the old string
* must be contained within slashes
EDIT operates by searching the line number that you specified for an exact match of the old string. If it finds a match it removes the old string and replaces it with the new string and displays the line so that you can inspect the change. If it is unable to find a match it reports failure and no change is made.
EDIT searches for the old string from left to right and makes the change on the first match it makes.
LIST 20 [Return]
TEST 1-FEB-1991 12:25
20 PRINT "HELLO THERE"
Ready
EDIT 20 /HELLO/GOODBYE/ [Return]
20 PRINT "GOODBYE THERE"
Ready
The preceding example of changing the word HELLO to GOODBYE in statement 20 is almost as much work as retyping the entire line.
Consider the following:
LIST 40 [Return]
TEST 1-FEB-1991 12:26
40 PRNT "Welcome to the Income Tax Evasion Program"
Ready
EDIT 40/RN/RIN/ [Return]
40 PRINT "Welcome to the Income Tax Evasion Program"
Ready
Here the saving in time is obvious. The key to using EDIT and saving typing effort is to minimize the length of the old string, while still ensuring that it is unique. The same effect as above could have been achieved with the EDIT command:
EDIT 40 /R/RI/ [Return]
Consider the following attempt to get rid of an extra T by changing it into nothing:
LIST 110 [Return]
TEST 1-FEB-1991 12:26
110 PRINT "ITT'S TIME FOR TEA"
Ready
EDIT 110 /T// [Return]
110 PRIN "ITT'S TIME FOR TEA"
Ready
EDIT scanned the statement from left to right and matched the T in the word PRINT and replaced it with nothing. There are two ways around this problem. One way is to put enough characters in the old string to make it unique.
For example:
LIST 110 [Return]
TEST 1-FEB-1991 12:28
110 PRINT "ITT'S TIME FOR TEA"
Ready
EDIT 110 /TT/T/ [Return]
110 PRINT "IT'S TIME FOR TEA"
Ready
There is only one occurrence of the old string TT in the statement so there is no confusion. The other solution is to specify which occurrence of the old string EDIT should use for the operation. This is done by adding an occurrence number to the end of the EDIT command:
LIST 110 [Return]
TEST 1-FEB-1991 12:29
110 PRINT "ITT'S TIME FOR TEA"
Ready
EDIT 110 /T//2 [Return]
110 PRINT "IT'S TIME FOR TEA"
Ready
If you have two errors on a line and they are far apart it is simpler to use two separate EDIT commands.
Note: Should you accidentally enter the EDIT command with nothing following you will have started the general purpose system editor. To get out of this situation, enter the QUIT command. (see "VMS System Editor" in the Editors Division of the Manual).
EDIT [Return]
1 10 PRINT "HELLO"
* QUIT [Return]
Ready
In the following program ASSIGN3 is loaded into BASIC's internal storage and another program called HEADER is appended. Care must be taken so that line numbers do not collide. Also note that the program in internal storage remains named ASSIGN3 after the APPEND command is issued.
OLD ASSIGN3 [Return]
Ready
LIST [Return]
ASSIGN3 1-FEB-1991 1:30
1000 PRINT " This program solves the age-old problems"
1010 PRINT " of life, death, taxes, and assignments"
1020 PRINT
1030 etc...
Ready
APPEND HEADER [Return]
Ready
LIST [Return]
ASSIGN3 1-FEB-1991 1:31
100 REM ---------------------------------------------
110 REM -
120 REM - Another fine software product brought
130 REM - to you by the infamous John Doe
140 REM -
150 REM ---------------------------------------------
1000 PRINT " This program solves the age-old problems"
1010 PRINT " of life, death, taxes, and assignments"
1020 PRINT
1030 etc...
Ready
APPEND can save you many hours of typing reusable program code and remarks.
Ready
$ DIRECTORY [Return]
DIRECTORY MEENA4:[UNDERGRAD.DOE1234J]
HELLO.BAS;1 LOGIN.COM;1 STUFF.BAS;1 TEST.BAS;1
TOOCLOSE.BAS;1
Total of 5 files.
Ready
DIRECTORY is the most useful command to execute in this way, but any system command can be used at any time from within BASIC without affecting the BASIC program you are working on. VMS system commands should not be considered part of BASIC's command set.
Note: Since any system command can be entered from within BASIC it is possible to start a BASIC environment from within a BASIC environment. DO NOT enter $BASIC from within BASIC.
HELP [Return]
You will be given a long list of topics upon which you can receive help. To select a topic enter its name after the Topic? prompt. Available information on that topic will be displayed along with a list of subtopics. Select a subtopic by entering it's name after the Subtopic? prompt.
The [Return] key reverses the preceding operation. Pressing [Return] after a Subtopic? prompt backs you up to the Topic? prompt and a [Return] key at the Topic? prompt gets you back to the BASIC Ready prompt.
You can save time when using HELP if you know what topic/subtopic that you are looking for.
BASIC HELP contains:
* BASIC Commands
i.e. to get HELP on the SAVE command:
HELP COMMANDS SAVE [Return]
* BASIC Statements (see "Program Statements" in Programming in BASIC)
i.e. to get HELP on the Print Statement:
HELP PRINT [Return]
* BASIC Built-in Functions (see "Predefined Functions" in Programming in BASIC)
i.e. to get HELP on the LEFT$ Function:
HELP LEFT$ [Return]
* BASIC Errors of two types (see "Making Sense of System Messages" in Program Debugging)
HELP COMP ERROR [Return]
HELP RUN ERROR [Return]
Ready
EXIT [Return]
$
When you leave BASIC its internal storage is cleared so remember to save your work. If you attempt to EXIT without saving your work, BASIC will remind you that you have made changes that have not been saved. At this point you can SAVE your work and then enter the EXIT command again, or you can enter the EXIT command without the SAVE to leave BASIC.
Ready
EXIT [Return]
%BASIC-W-CHANGES, unsaved changes have been made, CTRL/Z or EXIT to exit.
Ready
SAVE [Return]
%BASIC-I-FILEWRITE, TEST written to a file as
MEENA4:[UNDERGRAD.DOE1234J]TEST.BAS;1
Ready
EXIT [Return]
$
There are many different versions of BASIC. The BASIC programming language described below is specific to the version available on the VAX. While the core of the BASIC language is universal, VAX BASIC supports more instructions than most other versions of BASIC. For information regarding the use of other versions of BASIC on other computers for class work see Introduction to Labs).
Ready
PRINT 27+101 [Return]
128
Ready
Immediate mode can also be used to examine the contents of variables after a STOP has been executed. See "Debugging Example" in Program Debugging for an example.
When you enter a line into BASIC that begins with a line number, BASIC checks to see that its syntax is correct and then stores it away in internal storage. When you have entered all the lines of the program you can execute them with the RUN command. Here is an example of a complete program that adds one and two and displays the result:
NEW SMALL [Return]
Ready
10 LET X = 1 + 2 [Return]
20 PRINT X [Return]
30 END [Return]
RUN [Return]
SMALL 1-FEB-1991 12:15
3
Ready
The [Return] key is used to enter each line after it has been typed. At the end of each line, in the preceding example, we have displayed the [Return] key .In the additional examples in this manual the [Return] key has been omitted, however you may assume that it is employed at the end of each line to be entered.
* END must be the last statement in every program
* END statement must be the statement with the highest line number
* A program can contain a maximum of one END statement.
The exclamation mark (!) may also be used to add comments. The exclamation mark (!) can be used in the same way as a REM. The exclamation mark (!) can also be used to place a comment on the same line as a BASIC statement.
Ready
100 REM -----------------------------------------------
110 REM - This program computes the sum of
120 REM - the numbers from 1 to 5
130 REM -----------------------------------------------
150 !
160 LET TOTAL = 1 + 2 + 3 + 4 + 5 ! add up the numbers
170 PRINT TOTAL ! here is another remark
180 END
Note: avoid using several exclamation marks together as it confuses BASIC(for example: !!!).
Very small and very large numbers are represented by BASIC's own unique form of exponential notation. The number .00000008 is 8 x 10-8 in standard exponential notation. In BASIC's exponential notation this is .8E-07. The number 80,000,000 is 8 x 107 and .8E+08 in BASIC exponential notation.
Fractions are represented by decimal numbers. The number five and one quarter (5 1/4) is represented by 5.25.
Do not insert commas or $ signs in numbers. Use 50000 instead of 50,000. Use 10.50 instead of $10.50.
10 PRINT "The captain yelled, 'Man the Lifeboats!'"
20 END
RUN [Return]
NONAME 1-FEB-1991 12:22
The captain yelled, 'Man the Lifeboats!'
Ready
* an entity that can contain any of a number of different values.
* like a mailbox that can hold only one thing at a time.
* represented by a variable name.
When you name a variable in a program you reserve a location in BASIC's temporary memory that can contain a number or a collection of characters (character string).
Variable names have the following characteristics:
* can be up to 31 characters in length
* must begin with an alphabetic
* may contain only alphabetics, numerics, and underscores (no spaces)
* may not be the same as any of the list of BASIC's reserved words(see "BASIC Reserved Keywords" in the Appendix)
* character string variables have a $ as their last character.
Consider the following list of BASIC variable names:
COUNTER valid numeric variable name
TMP1 valid numeric variable name
TOTAL_PAY_THIS_WEEK valid numeric variable name
X$ valid string variable name
FIRST_NAME$ valid string variable name
1ST invalid (begins with a numeric)
LAST NAME$ invalid (contains a space)
PAY_RATE@WORK invalid (contains an illegal character)
PRINT invalid (PRINT is a BASIC reserved word)
* A numeric variable location which has not been initialized will be assigned the value of zero by the system.
* String variables name locations which will hold alphabetics, numbers and special characters.
* Everything stored in a string variable is stored and treated as letters.
* A string variable that contains 5 is said to contain the letter (or character) 5 instead of the numeric value 5.
* All string variables end with a $.
* A string variable location which has not been initialized (assigned a value) will be a null string (A string with no characters in it is defined to have length zero).
LET variable_name = expression
where the expression on the right side of the equal sign can be any of:
* a constant
* another variable
* an arithmetic expression (see "Expressions" in Programming in BASIC)
A LET statement operates by evaluating the expression on the right-hand side of the equal sign (if necessary) and storing the result in the variable on the left-hand side of the equal sign.
100 LET NUMBER = 4
110 LET SQUARE = NUMBER**2
120 LET WORD$=" SQUARED IS "
130 PRINT NUMBER;WORD$;SQUARE
140 END
RUN [Return]
NONAME 1-FEB-1991 12:34
4 SQUARED IS 16
Ready.
Line 100: The variable NUMBER stores the constant 4.
Line 110: The variable expression, NUMBER raised to the power 2, is evaluated. NUMBER contains 4. The result, 16 (i.e. 42), is stored in the variable SQUARE.
Line 120: The variable WORD$ stores a character string constant. Notice that the string constant is enclosed in quotes.
Line 130: The contents of all the variables are displayed by the PRINT statement.
Note: LET is the only BASIC statement where the verb itself can be omitted.
100 X = 10
works as well as
100 LET X = 10
All the examples in the above table are expressions.
1. BASIC looks at the expression to find any exponentiation (^ or **). Exponentiation is evaluated from right to left.
2. BASIC then looks for any multiplication (*) or division (/) and performs this from left to right.
3. BASIC then looks for any addition or subtraction and performs this from left to right.
Consider the following expression evaluation using BASIC's rules for precedence of operators:
Original Expression 10 - 2 * 3 ** 2 / 3 + 1
Step 1: Exponentiation (right to left) 10 - 2 * 9 / 3 + 1
Step 2: Multiplication and Division (left to right) 10 - 18 / 3 + 1
Step 3: Subtraction and Addition (left to right) 10 - 6 + 1
4 + 1
5
Parentheses may be used to make expressions easier to read and to modify the order in which operations are performed. BASIC performs operations inside parentheses first.
For example:
3 + 4 * 5 evaluates to 23
(3 + 4) * 5 evaluates to 35
When one set of parentheses is nested (contained within) another set the innermost set is evaluated first. For example:
(3 * ( 2 + 1) ) ** 2 evaluates to 81
When you are uncertain of the order of evaluation, use parentheses.
100 LET X$ = "HAPPY"
110 LET Y$ = "BIRTHDAY"
130 LET Z$ = X$ + Y$
140 PRINT Z$
150 PRINT Z$ + " JOE"
160 END
RUN [Return]
NONAME 1-FEB-1991 13:25
HAPPYBIRTHDAY
HAPPYBIRTHDAY JOE
Ready
INPUT variable_list
or
INPUT prompt_string ; variable_list (input will be printed on the same line)
or INPUT prompt_string , variable_list (input will be printed on the next line)
where:
variable_list is one or more variable names separated by commas.
prompt_string is an optional character string constant that contains information that helps the person using the keyboard decide what data to enter.
The INPUT statement causes the computer, during the execution of the program, to print a question mark on the terminal. The user at the keyboard then responds by typing the data required. Multiple data items are separated by commas. After the items are entered the user types the [Return] key. The computer then assigns the values entered to the corresponding variable names and continues executing the program.
100 PRINT "Please enter your name"
110 INPUT NAME$
120 PRINT "Hello ";NAME$
130 INPUT "Enter two numbers separated by a comma";FIRST,SECOND
140 LET TOTAL = FIRST + SECOND
150 PRINT "The sum of your numbers, ";NAME$;" , is";TOTAL
160 END
RUN [Return]
5-8-INPUT 1-FEB-1991 12:35
Please enter your name
? BIG JOE [Return]
Hello BIG JOE
Enter two numbers separated by a comma? 12.5,7 [Return]
The sum of your numbers, BIG JOE , is 19.5
Ready
Line 100: Prints a character string
Line 110: Prints a ? prompt; the user then enters his name and taps the [Return] key.
Line 120: Note the space after the character string Hello. If it was not there the words Hello and BIG would run together.
Line 130: Prints a prompt string followed by the INPUT (?) prompt. The user is able to enter the numbers on the same line as the prompt due to the placement of a semicolon at the end of the prompt string. Line 100 would benefit from a similar semicolon to allow the user to enter his name on the same line as the prompt. In fact, line 100 and line 110 could be combined with the addition of a prompt_string to line 110.
Line 140: Calculates the sum of the two input numbers
Line 150: Note that each item is separated with a semicolon---the more complex the PRINT statement, the more careful you must be to include all the semicolons. Also note the use of commas inside character string constants. Inside a pair of quotes commas are just another character to be printed.
* If the user fails to provide enough data to satisfy the INPUT statement it will continue printing ? prompts until the data requirements are satisfied.
* If the user supplies too many data items, INPUT ignores the last data items.
* If the user supplies a character string and INPUT is looking for a numeric, INPUT will be unable to store the characters in the numeric variable, so it will print an error message and another ? prompt. (see "Making Sense of System Messages" in Program Debugging)
* If the user wants to enter a character string that contains commas or semicolons, the string must be enclosed in quotes.
PRINT list_of_data
where the list_of_data consists of one or more of the following:
* Constants
* Variables
* Expressions
The PRINT statement prints string constants exactly as they appear. When a variable is encountered the value of the variable is printed. Expressions are evaluated and the result is printed.
100 LET X = 2 + 3
110 PRINT "X"
120 PRINT X
130 PRINT "2 + 3"
140 PRINT 2 + 3
150 END
RUN [Return]
NONAME 1-FEB-1991 12:45
X
5
2 + 3
5
Ready
Line 100: The sum of 2 and 3 is stored in the variable X.
Line 110: The character string constant "X" is printed.
Line 120: The value of the variable X is printed.
Line 130: The character string constant "2 + 3" is printed.
Line 140: The expression 2 + 3 is evaluated and the result it printed.(Immediate mode)
* Multiple items in a PRINT's list_of_data are separated by either commas (,) or semicolons (;) depending on how much space is required between the items. When a semicolon is used one item is printed immediately after another with no blank space between the two items. When a comma is used the items are separated by a tab. "Tab stops" are fixed to every 14 columns.
* A print line on a terminal may be regarded as a series of print zones. Each tab (comma) places you in the next print zone. The number of print zones on a line depends upon the width of your terminal.
* Normally the print head is moved to the next line at the end of a PRINT. However, when a semicolon or comma is placed at the end of a PRINT statement PRINT does not do a carriage return. This is used when you want to print something now, and later want to print more on the same print line.
* A number is printed, beginning at the second position of the print field with a trailing space printed after the number. The first print position is reserved for the arithmetic sign. If a number is positive, no sign is printed; the first position of the print field is blank. If a number is negative, a minus sign is printed in the first print position of the print field.
* Character strings are printed beginning at the first position of the print field.
* A print field is used for only one item, even if the item does not occupy all of the available print positions. Unused print positions in a field remain blank.
* Alphabetic, numeric, and alphanumeric items are left-justified within a print field.
* If a character string contains more characters than the maximum width of a print field, the computer will use additional print field(s) to print the character string.
* A comma or semicolon after the last item in a print statement causes the computer to continue printing on the same line if a PRINT statement is executed later in the program.
* The PRINT statement with no data items prints a blank line.
100 LET X = 2+3
110 PRINT "X", X, "2+3", 2+3
120 PRINT
130 PRINT "X"; X; "2+3"; 2+3;
140 PRINT "HELLO"
150 PRINT HELLO
160 PRINT "Y";Z$;"Y";W
170 END
RUN [Return]
NONAME 1-FEB-1991 12:50
X 5 2+3 5
X 5 2+3 5 HELLO
0
YY 0
Ready
Line 110: The data items are separated by commas, so each item starts in a new print field (separated by tabs).
Line 120: PRINT with no data items generates a blank line
Line 130: Data items are separated by semicolons, so there is no space left between items (numerics are preceded by a single space, strings are not).
Line 140: Line 130 has a semicolon at the end of it, so the string constant HELLO is printed on the same line.
Line 150: All uninitialized numeric variables have a value of zero.
Line 160: The uninitialized string variable location Z$ is a null string, having length zero, and has therefore no characters to print. The uninitialized numeric variable W has the value zero, which has been assigned by the system.
The READ statement causes the reading of data provided by one or more DATA statements. The general form of a READ statement is:
READ variable_list
The variable_list represents one or more variable names, separated by commas.
The DATA statement(s) contains the data that is to be read into variables by the READ statement. The general form of a DATA statement is:
DATA data_list
The data_list represents one or more data items, separated by commas. Character strings must be enclosed in quotes if they contain commas or semicolons.
When a READ statement is executed the entire program is scanned, starting at the first line, for a DATA statement. When one is located as many data items as are needed are taken from data and stored in the variable names specified by the READ. If there are not enough data items in the current DATA statement, another is sought. If another READ statement is encountered, it continues to look for data items where the last READ left off. Data items are not reused. If READ cannot find enough data items to satisfy all its variables, it produces an error message and the program stops execution.
It is helpful to think of a pointer that keeps track of which data item will be used for the next variable to be READ. At the start of the program, the pointer points to the first DATA item on the DATA statement with the lowest line number. Each variable read moves the pointer to the next data item.
100 READ NAME1$, AGE1
110 READ NAME2$, AGE2
120 READ NAME3$
130 READ AGE3
140 PRINT NAME1$; AGE1, NAME2$; AGE2, NAME3$; AGE3
150 PRINT "Total age is"; AGE1 + AGE2 + AGE3
160 DATA "BOB", 21, "MARY"
170 DATA 18
180 DATA BILL
190 DATA 45
200 END
RUN [Return]
5-8-READ 1-FEB-1991 12:56
BOB 21 MARY 18 BILL 45
Total age is 84
Ready
Line 100: Gets a value for NAME1$ and AGE1 from data; NAME1$ gets the first item of data available, which is "BOB" supplied by line 160.
Line 110: Gets two more values from data; NAME2$ from the third item on line 160 and AGE2 from the item on line. 170
Line 120: Gets a single item of data which is the item on line 180.
Line 130: Gets a single item of data which is the item on line 190.
Line 140: Prints the names and ages taking advantage of the sign position of the ages to leave a space between each name and its corresponding age.
Line 150: Calculates and prints the total age. Note the value of the expression AGE1+ AGE2 + AGE3 is calculated and only the result is printed.
Line 160-190: DATA statements are not executed.
Line 200: END.
* The location of the DATA statements in the program is irrelevant to the READ statement. The number of data items in each statement is also irrelevant, as long as there are at least as many data items as there are variables being READ.
* DATA statements are ignored when encountered while the program is executed.
* It is good programming practice to put all your DATA statements together at the end of your program, just before the END statement.
Once a data item is READ it cannot be READ again, unless you use a RESTORE statement. The RESTORE statement resets all DATA statements so that the next variable that is READ will again be the first data item in the first DATA statement (the data pointer is reset). The RESTORE statement is simply:
RESTORE
The RESTORE statement resets data items (data pointer) so that the next item that is READ is the first item of the first DATA statement in the program, regardless of how many items have been previously READ.
100 READ A,B,C
110 PRINT A;B;C
120 PRINT "THEIR SUM IS"; A + B + C
130 RESTORE
140 READ FIRSTNUM
150 PRINT "THE FIRST NUMBER IS"; FIRSTNUM
160 DATA 2,3,6,5
170 END
RUN [Return]
5-8-RESTORE 1-FEB-1991 12:59
2 3 6
THEIR SUM IS 11
THE FIRST NUMBER IS 2
Ready
Line 100: Get values from data for A, B and C.
Line 110: Print values of A, B and C.
Line 120: Print sum of A, B and C.
Line 130: RESTORE statement resets data pointer.
Line 140: The value read is the first item of data due to RESTORE. If the RESTORE statement was removed, the value for FIRSTNUM would be 5.
Line 150: Value of FIRSTNUM is output.
Line 160: DATA statement is not executable.
Line 170: END
GOTO line_number
where line_number is the BASIC line number of any line in your program.
Use of GOTO statements leads to problems in program code that have been overcome with a trend toward structured programming and enhancements to the BASIC language that have all but eliminated the use of the GOTO. Although an explanation of GOTO statements has been included in this manual, in fact they should NOT be used because they make the program flow difficult to follow (sometimes described as spaghetti code), which makes your program difficult to read, understand, and debug.
GOTOs are useful in a program that must branch over a section of code (usually a subroutine (see "Subroutines" in Prtogramming in BASIC)) to get to the END statement.
GOTOs should almost never appear in your programs!
Relational expressions are used by IF-THEN statements and WHILE statements.
Relational OperatorsHere are some sample relational expressions and their meanings:Symbol Meaning
> Greater than >= Greater than or equal to < Less than <= Less than or equal to = Equal to <> Not equal to
Relation MeaningX = 10 Numeric variable X equal to 10
X = Y Numeric variable X equal to numeric variable Y
X >= 50 Numeric variable X greater than or equal to 50
Z <> 5 Numeric variable Z is not equal to 50
X$ = "HI" Character variable X$ equal character string "HI"
X$ < Y$ Character variable X$ precedes Y$ in alphabetic sequence
X$ <> "END" Character variable X$ does not equal character string "END"
More complex conditions can be expressed by using AND or OR to combine relations together into more complex relations. For example, to see if the content of the numeric variable X is between 1 and 10:
X >= 1 AND X <= 10
The relation to determine if X$ is "Y" or "y" or "yes" or "YES" is:
X$ = "Y" OR X$ = "y" OR X$ = "YES" OR X$ = "yes"
IF relational_expression THEN statement
where:
relational_expression is a comparison of two values (or two expressions) with the use of a relational operator (see "Relational Expressions" in Programming in BASIC)
statement is any BASIC program statement that will be executed only if the relational_expression is true.
IF relational_expression THEN statement ELSE statement
where either the statement following the then or the statement following the ELSE is executed, but never both.
100 LET X = 20
110 IF X = 10 THEN PRINT "X = 10"
120 IF X = 20 THEN PRINT "X = 20"
130 IF X >= 20 THEN PRINT "X >= 20"
140 IF X = 5 THEN PRINT "X = 5" ELSE PRINT "X <> 5"
150 END
RUN [Return]
NONAME 1-FEB-1991 12:58
X = 20
X >= 20
X <> 5
Ready
Line 100: Initialize a variable for testing purposes
Line 110: X does not equal 10 so the THEN part is not performed
Line 120: X is 20 so the THEN part is performed
Line 130: X is greater than or equal to 20 ( in fact X = 20) so the THEN part is performed.
Line 140: X does not equal 5 so the ELSE part is performed.
Line 150: END
IF relational_expression THEN
statement(s)
END IF
or
IF relational_expression THEN
statement(s)
ELSE
statement(s)
END IF
Relational_expression is a valid relation (see "Relational Expressions" in Programming in BASIC), and statement(s) represent any number of BASIC program statements. Statement(s) are indented with a [Tab) to better show that they are only executed if the relational_expression is true. With the inclusion of an ELSE you can specify a set of statement(s) that are executed if the relational_expression is not true. Line numbers cannot be used between the IF and the END IF statements (see following example).
100 PRINT "Temperature Conversion Program"
110 PRINT
120 INPUT "Enter a temperature to be converted"; TEMP
130 INPUT "Is your temperature in CELCIUS or FAHRENHEIT";FORM$
140 PRINT
150 IF FORM$ = "CELCIUS" THEN
LET FAHRENHEIT = 9 / 5 * TEMP + 32
PRINT TEMP; FORM$; " ="; FAHRENHEIT; " FAHRENHEIT"
ELSE
LET CELCIUS = 5 / 9 * (TEMP - 32)
PRINT TEMP; FORM$; " ="; CELCIUS; " CELCIUS"
END IF
160 END
RUN [Return]
5-9-IF 1-FEB-1991 12:59
Temperature Conversion Program
Enter a temperature to be converted? 32 [Return]
Is your temperature in CELCIUS or FAHRENHEIT? CELCIUS [Return]
32 CELCIUS = 89.6 FAHRENHEIT
Ready
Line 100-140: Output user instructions
Line 150: Check the type of temperature that the user entered. If the type is CELCIUS then execute the lines before the ELSE.
* TEMP is in CELCIUS so convert it to Fahrenheit
* Output the result
* If the type is anything other than CELCIUS, the lines following the ELSE are executed. Note that if the user had entered Celcius or celcius, the ELSE would be executed as the match must be exact.
(ELSE) * TEMP is not in CELCIUS so assume it is in FAHRENHEIT and convert it to CELCIUS
* Output the result
(ENDIF) * Marks the end of the multi-line IF statement
Line 160: END
SELECT expression
CASE case_expression
statement(s)
.
.
.
CASE ELSE
statement(s)
END SELECT
where:
expression can be any expression but is usually a single variable. case_expression can be any of the following forms:
* expression (i.e. 10)
* relational_operator expression (i.e. >= 10)
* expression1 TO expression2 (i.e. 1 TO 10)
Case_expressions indicate which of the possible cases of the selected expression must be matched in order for the statement(s) following it to be executed. CASE ELSE is a special (optional) case whose following statement(s) are executed if none of the previous cases are matched.
Only one set of case statements is executed in a SELECT statement.
For example:
100 PRINT "Enter a grade in percentage and I'll convert it"
110 PRINT "to a letter grade A, B, C, D or F"
120 PRINT
130 INPUT "Enter a grade"; GRADE
140 SELECT GRADE
150 CASE < 50
160 LET LETTER$ = "F"
170 LET MESSAGE$ = "see you here next year"
180 CASE 50 TO 60
190 LET LETTER$ = "D"
200 LET MESSAGE$ = "you just scraped by"
210 CASE 60 TO 70
220 LET LETTER$ = "C"
230 LET MESSAGE$ = "middle of the road"
240 CASE 70 TO 79
250 LET LETTER$ = "B"
260 LET MESSAGE$ = "good work"
270 CASE 80 TO 100
280 LET LETTER$ = "A"
290 LET MESSAGE$ = "excellent"
300 CASE ELSE
310 LET LETTER$ = "HUH?"
320 LET MESSAGE$ = "a strange grade indeed"
330 END SELECT
340 PRINT GRADE; " is a(n) "; LETTER$
350 PRINT MESSAGE$
360 END
RUN [Return]
5-10-CASE 1-FEB-1991 12:59
Enter a grade in percentage and I'll convert it
to a letter grade A, B, C, D, E or F
Enter a grade? 49 [Return]
49 is a(n) F
see you here next year
Ready
Line 100-120: Print user instructions.
Line 130: Get a numeric grade from the user.
Line 140: SELECT the GRADE variable. All cases now refer to the variable GRADE
Line 150: When it is the CASE that the GRADE is less than 50, statements 160-170 are executed. A letter grader (F) is assigned to the letter variable and the message is printed.
.
.
.
Line 300: If none of the previous cases matched, then the statements following the CASE ELSE are executed.
Line 330: END SELECT marks the end of a SELECT statement.
Line 340-350: Print the letter grade and message that was assigned by the SELECT statement.
Line 360: END
100 LET COUNTER = 1
110 INPUT "Enter your name"; NAME$
120 WHILE COUNTER <= 5
130 PRINT COUNTER, NAME$
140 LET COUNTER = COUNTER + 1
150 NEXT
160 END
RUN [Return]
5-11-LOOP 1-FEB-1991 12:59
Enter your name? JOHN DOE [Return]
1 JOHN DOE
2 JOHN DOE
3 JOHN DOE
4 JOHN DOE
5 JOHN DOE
Ready
Line 100: Set 'COUNTER' to 1.
Line 110: Get the user's name.
Line 120: Enter the loop while the condition is true. (COUNTER <=5)
Line 130: Print the contents of the variable 'COUNTER' and 'NAME'.
Line 140: Count the number of cycles of the loop by adding one to the previous counter and storing the result in 'COUNTER'.
Line 150: Return to the beginning of the loop.(Line 120). Check counter. If it is less than or equal to 5 then we still have not printed 'NAME' 5 times so print it again. If 'COUNTER' is no longer less than or equal to 5, we have printed 'NAME' 5 times so end.
Line 160: End of program.
Because looping is used so much in programming, there are special statements to make the job easier and which help to avoid the unstructured spaghetti code that can come from the use of branching.
FOR variable = initial_value TO limit STEP incrementHere is a program that will print the numbers from 99 to 50 in reverse order, 10 numbers to a line. Note that when you cannot come up with a better name for your loop counters, the variable names I, J, and K are traditionally used (this tradition can be traced to its roots in the FORTRAN programming language). See "Print Using" in "Formatting Output" in Programming in BASIC for a discussion of PRINT USING. See "Predefined Functions" in Programming in BASIC for a discussion of the INT function.statement(s)
.
.
NEXT variable
where
variable must be a numeric and must be the same variable for both the FOR and the NEXT statements.
initial_value is the value given to the variable before the statement(s) are first executed.
limit is the terminating condition for the loop. When the variable is greater than the limit the loop terminates.
STEP and increment are optional. They specify by what amount the variable should change on each successive iteration of the loop. If the STEP is excluded the default of STEP 1 is used. Statement(s) are indented by a [Tab) to show that they are all part of the same loop.
100 INPUT "Enter your name"; NAME$
110 FOR COUNTER = 1 TO 5 STEP 1
120 PRINT COUNTER,NAME$
130 NEXT COUNTER
140 END
RUN [Return]
5-11-FORLOOP 1-FEB-1991 12:59
Enter your name? JOHN DOE [Return]
1 JOHN DOE
2 JOHN DOE
3 JOHN DOE
4 JOHN DOE
5 JOHN DOE
Ready
This program does the same thing as the previous looping example (see "Looping" in Programming in BASIC").
Line 100: Get the user's name
Line 110: Start of loop. First time through the loop the counter variable COUNTER is initialized to 1. On each iteration COUNTER is incremented (increased) by 1. When COUNTER is greater than 5 execution of the loop stops and the statement following the NEXT statement is executed.
Line 120: Print the contents of the loop counter and the user's name.
Line 130: NEXT marks the end of the loop. When the NEXT is encountered, the STEP size is added to the loop counter and the loop counter is checked against 5 to determine if the loop should be executed again.
Line 140: End
STEP sizes may be positive, negative, whole, or real numbers. For example a program that will print odd numbers from 1 to 15 would look like:
100 FOR ODD = 1 TO 15 STEP 2
110 PRINT ODD;
120 NEXT ODD
130 END
RUN [Return]
5-11-FORODD 1-FEB-1991 12:59
1 3 5 7 9 11 13 15
Ready
100 FOR I = 99 TO 50 STEP -1110 PRINT USING "####",I;
120 IF I / 10 = INT(I / 10) THEN PRINT
130 NEXT I
140 END
RUN [Return]
5-11-FOR100 1-FEB-1991 13:03
99 98 97 96 95 94 93 92 91 90
89 88 87 86 85 84 83 82 81 80
79 78 77 76 75 74 73 72 71 70
69 68 67 66 65 64 63 62 61 60
59 58 57 56 55 54 53 52 51 50
Ready
Line 110: For a further explanation of PRINT USING see "Formatting Output" in Programming in BASIC
Line 120: For a further explanation of INT see "Predefined Functions" in Programming in BASIC
You may use as many loops in a program as you want. You may also nest one loop inside another. Make sure that the inner loop is completely contained within the outer loop and that the loops have different control variables.
FOR I = 1 TO 10
FOR J = 1 TO 5
statement(s)
NEXT J
NEXT I
The statements in the above example would be executed a total of 50 times: the outer loop executes 10 times and each time, the inner loop executes 5 times.
WHILE relational_expression
statement(s)
.
.
.
NEXT
where:
relational_expression is any valid relational (see "Relational Expressions" in "Selection" in Programming in BASIC)
NEXT marks the end of the loop. Statement(s) are indented to show visually that they are all part of the same loop.
The WHILE loop operates by executing the statement(s) while the relational_expression is true. When the relational_expression becomes false, the loop terminates. The next statement that is executed is the one that follows the NEXT statement.
100 INPUT "Enter a name (LAST to end)"; NAME$
110 WHILE NAME$ <> "LAST"
120 PRINT NAME$
130 INPUT "Enter a name (LAST to end)"; NAME$
140 NEXT
150 END
RUN [Return]
5-11-WHILE 1-FEB-1991 13:05
Enter a name (LAST to end)?.JOE [Return]
JOE
Enter a name (LAST to end)? MARY [Return]
MARY
Enter a name (LAST to end)? FRED [Return]
FRED
Enter a name (LAST to end)? LAST [Return]
Ready
Line 100: Get an initial name from the user
Line 110: Execute statements 120-130 as long as the name the user enters is not the character string "LAST"
Line 120: Print the name
Line 130: Get another name from the user
Line 140: Next marks the end of the WHILE loop
Line 150: END
Print Format
TAB(X) Used in PRINT statements to format output. X specifies an absolute print position (an absolute column to start printing the next field at)
SPACE$(X) Used in PRINT statements to indicate how many blank spaces should exist between data items(relative spacing)
STRING$(N,C) A string of N characters with numeric ASCII code C is created
100 PRINT TAB(10); "HELLO"; TAB(30); "THERE"
110 PRINT SPACE$(10); "HELLO"; SPACE$(30); "THERE"
120 PRINT STRING$(50,97)
130 END
RUN [Return]
NONAME 1-FEB-1991 12:59
HELLO THERE
HELLO THERE
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
Ready
Line 100: Tab to column 10, print "HELLO", tab to column 30 and print "THERE"
Line 110: Print 10 spaces, print "HELLO", print 30 more spaces, and print "THERE"
Line 120: Create a string of 50 ASCII character 97s (lowercase a) and print it.
See "Predefined Functions" in Programming in BASIC for a discussion of predefined functions.
PRINT USING format_string; variables
where
format_string is a character string or string variable that contains specific formatting characters
variables are inserted into the format_string and the string is printed.
Character String Formatting
All character string format characters must start with a single quotation mark ('). The quotation mark reserves one character position. Formatting characters:
L Reserves one character position and left-justifies the field
R Reserves one character position and right-justifies the field
C Reserves one character position and centers the field
E Reserves one character position and expands the field to hold the entire field
Example:
100 LET X$ = "MOM"
110 PRINT USING "Hello there, 'LLLLLLLLLLLLLLLLLL", X$
120 PRINT USING "Hello there, 'RRRRRRRRRRRRRRRRRR", X$
130 PRINT USING "Hello there, 'CCCCCCCCCCCCCCCCCC", X$
140 PRINT STRING$(34,97)
150 END
RUN [Return]
5-12-USINGSTRING 1-FEB-1991 12:59
Hello there, MOM
Hello there, MOM
Hello there, MOM
Ready
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
Line 100: Initialize a character string for testing purposes
Line 110: MOM is printed LEFT-justified in the field
Line 120: MOM is RIGHT-justified in the field
Line 130: MOM is CENTERED in the field
Line 140: Create a string of 50 ASCII character 97s (lowercase a) and print it.
Line 150: END
Note: character strings that are not preceded by a single quote (') are treated as character string literals.
Numeric Formatting
The numeric formatting characters are:
# Reserves one space for a sign or digit
, Inserts commas before every third digit to the left of the decimal point
. Inserts a decimal point
$$ Reserves space for a $ and one digit
** Fills the left side of the field with asterisks (*) and reserves space for two digits (i.e. for amounts on cheques)
- Prints negative numbers with a trailing minus sign for budding accountants
For example:
100 LET A = 5.556
110 LET B = -5.556
120 LET C = 123456.556
130 LET D = -123456.556
140 PRINT USING "#####", A, B, C, D
150 PRINT USING "##.##", A, B, C, D
160 PRINT USING "$$##,###,###-", A, B, C, D
170 PRINT USING "$**#,###,###.##-", A, B, C, D
180 PRINT
190 F$ = "The 'CCCCCCCCCC are favored over "
200 F$ = F$ + "the 'CCCCCCCCCC by ##.## points"
210 READ TEAM1$, TEAM2$, SPREAD
220 WHILE TEAM1$ <> "DUMMY"
230 PRINT USING F$, TEAM1$, TEAM2$, SPREAD
240 READ TEAM1$, TEAM2$, SPREAD
250 NEXT
260 DATA "Canucks", "Leafs", 5.55555
270 DATA "FLAMES", "CANDLES", 23.9
280 DATA "Lions", "Lambs", 123.0
290 DATA "Extraterrestrials", "49ers", 2
300 DATA "NONAME Micros", "IbeeM BS/2", 0
310 DATA "DUMMY', "DUMMY", 0
320 END
RUN [Return]
5-12-USINGNUM 1-FEB-1991 13:35
6
-6
% 123457
%-123457
5.56
-5.56
% 123457
%-123457
$6
$6-
$123,457
$123,457-
$**********5.56
$**********5.56-
$****123,457.00
$****123,457.00-
The Canucks are favored over the Leafs by 5.56 points
The FLAMES are favored over the CANDLES by 23.90 points
The Lions are favored over the Lambs by % 123 points
The Extraterres are favored over the 49ers by 2.00 points
The NONAME Micr are favored over the IbeeM BS/2 by 0.00 points
Ready
The general form of a function is a three (or more) letter function name followed by one or more comma separated arguments contained within parenthesis.
Functions sometimes return (result in) a value or string of characters. These returned items should be stored in a variable. You can use them later in your program, as part of an expression, or you may print them immediately. Functions that return character strings have a $ as the last letter of their function name.
RESULT = FUNC(X,Y)
or
RESULT$ = FUNC$(X$,Y)
Where:
* FUNC is the name of a function that returns a numeric.
* FUNC$ is the name of a function that returns a character string.
* X and Y are arguments to the function.
Trigonometric Functions
SIN(X) returns the sine of angle X specified in radians
COS(X) returns the cosine of angle X specified in radians
TAN(X) returns the tangent of angle X specified in radians
ATAN(X) returns the angle, in radians, of a specified tangent X
Exponential Functions
EXP(X) Natural exponent ex is calculated
LOG(X) Natural logarithm logex is calculated
SQR(X) The square root of X is calculated or use SQRT(X)
Arithmetic Functions
ABS(X) Absolute value of X is determined
SGN(X) Sign of X is determined (result is either -1, 0, or +1)
INT(X) Truncate X (result is X without fractional part)
For example:
100 PRINT SQR(36)
110 PRINT ABS(-99); ABS(0); ABS(99)
120 PRINT SGN(-999), SGN(0), SGN(999)
130 PRINT INT(-9), INT(9/2), INT(-9.999999)
140 END
RUN [Return]
NONAME 1-FEB-1991 12:59
6
99 0 99
-1 0 1
-9 4 -10
Ready
Character Conversions
ASCII(X$) ASCII decimal value of first character in X$ is returned
CHR$(X) ASCII decimal value X is converted to a character and returned
VAL(X$) Return numeric value of X$ (which contains only numeric characters)
For example:
100 LET X$ = "A"
110 PRINT ASCII(X$), CHR$(65)
120 PRINT "--------"
130 LET X$ = "123.45"
140 LET NUMBER = VAL(X$)
150 PRINT NUMBER + 50
160 END
RUN [Return]
NONAME 1-FEB-1991 12:59
65 A
--------
173.45
Ready
Info about a string
LEN(X$) Returns the length (number of characters) in X$
INSTR(n,X$,Y$) Search the string X$ starting at the nth character of X$, for an exact match of the string Y$. If a match is found its starting position in X$ is returned. If no match, then zero (0) is returned.
For example:
100 LET X$ = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
110 PRINT LEN(X$)
120 PRINT INSTR(1,X$,"H")
130 PRINT INSTR(1,X$,"WXY")
140 PRINT INSTR(10,X$,"A")
150 END
RUN [Return]
NONAME 1-FEB-1991 12:59
26
8
23
0
Ready
Substrings
LEFT$(X$,n) Return a substring of X$ from the leftmost character of X$ to the nth character of X$
RIGHT$(X$,n) Return a substring of X$ beginning at the nth character and ending at the rightmost character of X$
MID$(X$,n1,n2) Return a substring of X$ which begins at the n1 character and is n2 characters in length
For example:
100 LET X$ = "Show me the way to go home"
110 PRINT LEFT$(X$,4)
120 PRINT LEFT$(X$,14)
130 PRINT RIGHT$(X$,23)
140 PRINT RIGHT$(X$,14)
150 PRINT MID$(X$,6,10)
160 PRINT MID$(X$,9,1)
170 END
RUN [Return]
NONAME 1-FEB-1991 12:59
Show
Show me the wa
home
ay to go home
me the way
t
Ready
Print Format
TAB(X) Used in PRINT statements to format output. X specifies a print position (see "Print Functions" in "Formatting Output" in Programming in BASIC)
SPACE$(X) Used in PRINT statement to indicate how many blank spaces should exist between data items (see "Print Functions" in "Formatting Output" in Programming in BASIC)
Random Numbers
RND Randomly generate a number greater than or equal to 0 but less than 1.
For example:
100 PRINT RND
110 PRINT RND
120 PRINT RND
130 END
RUN [Return]
NONAME 1-FEB-1991 12:59
.763081
.179978
.902878
Ready
The numbers that are generated by the RND function are always between 0 and .999999. You must scale these numbers up to the form of random number that you require. For example, if you require random whole numbers between 1 and 10 use INT(RND * 10) + 1. RND * 10 gives you random numbers between 0.00000 and 9.99999. Taking the integer part of the number gives you random numbers between 0 and 9. Adding 1 to the result give you numbers in the range 1 to 10.
RND always generates the same sequence of random numbers for each program run. To generate truly random numbers that are different for each program run, add the RANDOMIZE statement to the start of your program.
100 RANDOMIZE
120 PRINT "The six winning numbers for LOTO 649 this week are:"
130 FOR I = 1 to 6
140 PRINT INT(RND * 49) + 1,
150 NEXT I
160 END
RUN [Return]
5-13-RANDOM 1-FEB-1991 13:45
The six winning numbers for LOTO 649 this week are:
23 45 16 7 2 35
Ready
RUN [RETURN]
5-13-RANDOM 1-FEB-1991 13:45
The six winning numbers for LOTO 649 this week are:
43 12 4 37 39 19
Ready
Date and Time
DATE$(0) Returns a character string which contains the date of the program run in the format dd-mmm-yy (i.e. 15-Jun-87)
TIME$(0) Returns a character string which contains the time of day in the format: HH:MM AM or HH:MM PM (i.e. 12:56 AM)
SLEEP(n) Program execution is suspended for n seconds.
100 PRINT "Today's date is: "; DATE$(0)
110 PRINT "The correct time is: "; TIME$(0)
120 PRINT "All this talking has made me tired, ";
130 PRINT "I'm going to take a nap"
140 SLEEP(30)
150 PRINT "I feel much better, ";
160 PRINT "I must have slept for about 30 seconds,"
170 PRINT "which is a long time for a computer to be asleep"
180 PRINT "The time is now:";TIME$(0)
190 END
RUN [Return]
NONAME 1-FEB-1991 13:35
Today's date is: 1-FEB-1991
The correct time is: 1:35 PM
All this talking has made me tired, I'm going to take a nap
I feel much better, I must have slept for about 30 seconds,
which is a long time for a computer to be asleep
The time is now: 1:36 PM
Ready
The BASIC language has arrays to solve this problem. An array is a list of locations (cells) in computer storage that is given a single variable name and whose individual cells are accessed using the array's variable name and subscripts.
In mathematics, subscripts are widely used. If you need four variables in math you can use A1 A2 A3 and A4. The 1,2,3 and 4 are called subscripts and A1 is read as "A sub one". A1 is impossible to enter at most terminals so the subscript is placed in parenthesis for BASIC programming. In BASIC A1 A2 A3 and A4 would become A(1) A(2) A(3) and A(4). The word index may be used as a synonym for subscript.
The array A could be pictured like this:
Array A
Cell A(1) [ ]
Cell A(2) [ ]
Cell A(3) [ ]
Cell A(4) [ ]
This section covers one-dimensional arrays (see "Two Dimensional Arrays" in Advanced BASIC). One-dimensional arrays are also known as lists or vectors.
DIM array_name(size)
where:
array_name can be any valid variable name
size indicates the maximum number of items the array must store. You may dimension several arrays with a single DIM statement by separating them with commas.
The rules for naming arrays are the same as those for naming regular variables. Both numeric and character string arrays are possible.
DIM A(4), NAME$(50), PHONE(15)
would setup the arrays:
A - a numeric array with 4 cells A(1), A(2), A(3), and A(4)
NAME$ - character string array with 50 cells NAME$(1), NAME$(2), NAME$(3), NAME$(4), ..., NAME$(50)
PHONE - numeric array with 15 cells PHONE(1), PHONE(2), PHONE(3), PHONE(4), ..., PHONE(15)
If you neglect to DIM an array, BASIC will automatically setup an array of 10 cells. This feature should not be used. Always remember to DIM all the arrays that you use.
Arrays that you DIM actually contain an extra cell with a subscript of 0 (zero). The array dimensioned as A(4) really contains 5 cells, A(0), A(1), A(2), A(3), and A(4). In general it is best to ignore this cell to avoid confusion.
Note: You can use the "same" name for character string, numeric, character string array, and numeric array variables (i.e. X, X$, X(10), X$(10)) and BASIC will treat them all separately. This should be avoided to prevent confusion.
100 DIM A$(8)
110 FOR I = 1 TO 8
120 READ A$(I)
130 PRINT I, A$(I)
140 NEXT I
150 DATA "THIS","IS","THE","WAY","WE","LOAD","AN","ARRAY"
160 END
RUN [Return]
NONAME 1-FEB-1991 13:35
1 THIS
2 IS
3 THE
4 WAY
5 WE
6 LOAD
7 AN
8 ARRAY
Ready
Line 100: Dimension an array called A$ with 8 cells named A$(1), A$(2), A$(3), A$(4), A$(5), A$(6), A$(7), and A$(8).
Line 110: Start of a loop that goes from 1 to 8. The variable "I" will be used as a subscript for the array A$. Could be phrased as "FOR EACH ELEMENT IN THE ARRAY A$ DO THE FOLLOWING"
Line 120-130: Read a value from data into the cell of array A, indicated by the subscript "I". Print the value of the subscript variable "I" and the contents of the array cell A$(I)
Line 140: NEXT marks the end of the loop
Line 150: DATA statement containing strings to be read into the array. Note that quotes did not have to be included in this case(see "READ/DATA/RESTORE" in "Input and Print" in Programming in BASIC).
Line 160: END
The above results could have been handled without an array as the use of more than one data item at once is not required. Consider the following program that reads names and phone numbers from data into two one-dimensional arrays. It then allows the user to search for a phone number by entering a name. When a match is made in the name array the same subscript is used to access the corresponding cell in the phone number array.
100 DIM NAME$(50), PHONE(50)
110 LET COUNTER = 1
120 READ NAME$(COUNTER), PHONE(COUNTER)
130 LET F$ = "Entry number ##: You can reach 'LLLLL at #######"
140 WHILE NAME$(COUNTER) <> "DUMMY"
150 LET COUNTER = COUNTER + 1
160 READ NAME$(COUNTER), PHONE(COUNTER)
170 NEXT
180 PRINT "LOADED "; COUNTER - 1; " NAMES AND NUMBERS"
190 INPUT "Who would you like to call (QUIT to end)";NEWNAME$
200 WHILE NEWNAME$ <> "QUIT"
210 FOR I = 1 TO COUNTER
220 IF NAME$(I) = NEWNAME$ THEN
PRINT USING F$, I, NAME$(I), PHONE(I)
END IF
230 NEXT I
240 INPUT "Name to call (QUIT to end)"; NEWNAME$
250 NEXT
260 DATA "JOE", 5493030
270 DATA "MARY", 5496767
280 DATA "JANE", 3457878
290 DATA "BRUCE", 3592310
300 DATA "JACK", 7876969
310 DATA "DUMMY",0
320 END
RUN [Return]
5-14-ARRAY 1-FEB-1991 13:35
LOADED 5 NAMES AND NUMBERS
Name to call (QUIT to end)? JOE [Return]
Entry number 1: You can reach JOE at 5493030
Name to call (QUIT to end)? JACK [Return]
Entry number 5: You can reach JACK at 7876970
Name to call (QUIT to end)? BETTY [Return]
Name to call (QUIT to end)? QUIT [Return]
Ready
Subroutines are "mini-programs" that you include with the "main program". The main program (calling program) transfers control to the subprogram, the subprogram completes its operation and control is shifted back to the main program. Subroutine calls look much like GOTO statements but differ in that control is always transferred back to the statement following the call. Using subroutines is structured because they function in a well-defined way, while GOTOs have no automatic controls built-in to them.
Subroutines are also know as subprograms, modules, and routines.
The general form of the GOSUB statement is:
GOSUB line_number
where line_number is the line number of the first statement of the subroutine.
RETURN
transfer control to the statement immediately following the most recently executed GOSUB.
* GOSUB should be the only statement that allows access to the subroutine
* RETURN should be the only means of exiting a subroutine.
* A subroutine may have more than one RETURN statement in it.
* Since subroutines are miniprograms each should be documented in much the same way as your main program is, with a header of comments that describes what the subroutine does and what variables it uses.
* One subroutine can call another subroutine.
100 REM This program abuses subroutines to show how they work
110 PRINT "Start of Main Program"
120 GOSUB 180
130 PRINT "Back in Main Program"
140 GOSUB 280 ! using a line number
150 PRINT "Back in Main again"
160 GOTO 310
170 !
180 PRINT "In SUB1"
190 GOSUB 230
200 PRINT "Back in SUB1"
210 RETURN
220 !
230 PRINT "In SUB2"
240 GOSUB 280
250 PRINT "Back in SUB2"
260 RETURN
270 !
280 PRINT "In SUB3"
290 RETURN
300 !
310 PRINT "All done"
320 END
RUN [Return]
NONAME 1-FEB-1991 13:35
Start of Main Program
In SUB1
In SUB2
In SUB3
Back in SUB2
Back in SUB1
Back in Main Program
In SUB3
Back in Main again
All done
Ready
* Another example of a gosub is as follows:
100 ! Main Program
110 DIM X(10)
120 PRINT "Numbers before sort:";
130 FOR I = 1 TO 10
140 READ X(I)
150 PRINT X(I);
160 NEXT I
170 PRINT
180 GOSUB 240
190 PRINT "Numbers after sort:";
200 FOR I = 1 TO 10
210 PRINT X(I);
220 NEXT I
230 GOTO 350
240 ! Sort Subroutine
250 CHANGE$ = "YES"
260 WHILE CHANGE$ = "YES"
270 CHANGE$ = "NO"
280 FOR I = 1 TO 9
290 IF X(I) > X(I+1) THEN
TEMP = X(I)
X(I) = X(I+1)
X(I+1) = TEMP
CHANGE$ = "YES"
END IF
300 NEXT I
310 NEXT
320 RETURN
330 !
340 DATA 9, 8, 4, 1, 14, 55, 2, 0, 50, 3
350 END
RUN [Return]
5-15-GOSUB 1-FEB-1991 03:57
Numbers before sort: 9 8 4 1 14 55 2 0 50 3
Numbers after sort: 0 1 2 3 4 8 9 14 50 55
Ready
Initialization Dimension arrays Set variables to initial value Clear counters
Main Program Program statements GOTO END to avoid falling into subroutines
Subroutine A Subroutine A's statements return
Subroutine B Subroutine B's statements return
Data Data statements Data statement with sentinel (last) item
END End must be the last statement
Arithmetic Quiz Program
Write a program that could be used by an elementary school teacher to quiz his/her students on addition, subtraction, and multiplication. Questions posed should contain randomly generated integer numbers between 0 and 100. This is an elementary school so no questions that result in negative or fractions should be posed. Ask 20 questions and then print the students number correctly answered, and his/her percentage.
Heads and Tails
Write a program to keep track of the results of the flips of a coin for a gambler. Allow the program user to enter a guess of HEADS or TAILS, then use the RND function to "flip" the coin. Print a message indicating whether or not the user's guess was correct. When the user enters a guess of STOP, print a percentage of heads vs. tails and the longest consecutive "run" of heads or tails (i.e. if the results of a series of coin tosses are H H H T T T T H H T H T H H T T H then the longest run is four tails in a row).
Word Count
Write a program to input a sentence and output the number of words in the sentence. The sentence will end with a period and contain no other periods. A word is defined as any continuous string of non-space characters.
For example: the following sentence has 10 words:
A long time ago, came a man on a track.
Vowel Count
Write a program to input a sentence and output the number of each kind of vowel (A, E, I, O, and U) in the sentence.
Making Change
Write a program that calculates the number and type of coins required to make change for any input amount of money. The total number of coins should be the minimum required to make up the amount. The input amount of money will be entered in an integer value in pennies (i.e. $1.25 = 125cents). Coins that are available for change:
* Silver Dollars 100cents * Nickels 5cents
* Quarters 25cents * Pennies 1cents
* Dimes 10cents
Order
Write a program to get 59 numbers from input and then determine if they were entered in increasing order.
Inches Conversion
Write a program to convert a number of inches to feet and inches. There are 12 inches in a foot.
Reverse Numbers
Write a program to input 5 numbers into an array and a subroutine to print the numbers in reverse order.
Reverse Characters
Write a program to input a character string and output it in reverse order.
Vertical Characters
Write a program to input a character string and output it, one line per character. i.e.
Input: HELLO Output: H
E
L
L
O
Number Crunching
Write a program to read a group of numbers from data until a -1 is encountered. Compute/determine and print the sum, average, largest, and smallest number.
Columns
Write a program that will read character stings from data until the string DUMMY is encountered. Split the character strings in half and print them in two columns.
For example:
500 DATA GOODLUCK
510 DATA NOKILLI
520 DATA FIRSTANDTEN
530 DATA DUMMY
would produce:
GOOD LUCK
NOKI LLI
FIRSTA NDTEN
Paycheques
Greasy Dan's Carwash requires you to write a program to calculate gross pay, net pay, and print a paycheque (well, at least a reasonable facsimile). Get the employee's name, regular hourly wage, and hours worked this week.
* employees are paid weekly
* employees are paid overtime for any hours over 40
* overtime pay rate is 1.5 times regular rate
* Canada Pension Plan (CPP) deductions are 5% of gross wage
* Income Tax deductions are 25% of gross wage
Speeding Tickets
Write a program to help your local municipal officers do their job more efficiently by printing speeding tickets. You will be given the driver's name, vehicle registration number, speed limit, and speed recorded. Speeding fines are based on a flat $30.00 fee for speeding plus $2.50 for each kilometer per hour the limit was exceeded by. (i.e. going 30kph in a 25kph zone generates a fee of $42.50). Format the ticket in any way you like but include all pertinent information.
Pizza Cost
Write a program that will compute the cost per square inch for pizzas to determine the best value. Pizza data consists of a pizza name, the pizza diameter, and the total cost of the pizza. Read pizza data until you read a pizza named DUMMY. Output a table of pizza names and their cost per square inch. Also indicate which is the best value. Recall the formula to compute the area of a circle:
Area of a circle = [[pi]]r2
where [[pi]] = 3.14159 and r = radius of the circle
For example:
1050 DATA "Super Extra Large", 22, 23.50
1060 DATA "Extra Large", 18, 16.95
1070 DATA "Large", 15, 12.35
1080 DATA "Medium", 12, 9.12
1090 DATA "Small", 8, 6.78
1100 DATA "DUMMY", 0, 0
Character Histogram
Write a program to read from DATA statements, a collection of strings, and to print a VERTICAL histogram (bar graph) representing the occurrences of each letter of the alphabet in the strings. The string "*END*" terminates the data. You can assume that no lower case letters will appear in the DATA.
The following DATA statements:
500 DATA "THE QUICK BROWN FOX JUMPED OVER THE LAZY DOG."
510 DATA "THIS IS AN EXAMPLE OF HOW"
520 DATA "TO TEST YOUR HISTOGRAM PROGRAM, YOU"
530 DATA "CAN USE THIS EXAMPLE."
540 DATA "*END*"
should produce a vertical histogram in the following format:
* * *
* * * * *
* * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * *
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Compounded Interest
Write a program to calculate the amount of money generated by an amount of money that has been invested at a given rate of interest compounded annually for a predetermined number of years. The formula is:
A = P(1 + R)N
where:
A = amount P = principle invested
R = annual interest rate N = number of years
Examples Sample Statement What's wrong with it
Typing mistakes 100 PRNT "HELLO" Missed the I in PRINT
Punctuation 100 PRINT "HI No terminating quote
Order 100 FOR I = 1 STEP 3 TO 2 STEP in wrong place
Nonsense 100 PUT 7 IN X Makes no sense to BASIC although it may make sense to you
Syntax errors are easy to fix. BASIC points out exactly what is wrong and where in the statement it encountered the error. Simply read the error message (see "Making Sense of Error Messages" in Program Debugging) and repair the line in error (see "Edit" in "Altering a BASIC Program" in "The BASIC Environment").
The following table lists some examples of run-time errors:
Examples Sample Statement(s) What's wrong with it
Division by zero 100 LET ANSWER = X / 0 The result of anything divided by zero is "undefined" so BASIC is unable to continue. Fatal
Data format error 100 READ X An attempt was made during an 110 DATA "HELLO" INPUT or READ operation to place a character string into a numeric. Nonfatal.
Out of Data 100 READ X, Y, Z There is not enough DATA to 110 DATA 1, 2 satisfy the READ requirements. Fatal.
Overflow 100 LET Z = 999**999 The result of 999999 is so large that the computer cannot store it
Repairing run-time errors is also relatively easy. The error is pointed out during a program RUN and you can add more DATA statements or add IF statements before any LET that may divide by zero. You cannot design a program that will stop a user from entering a character string when you are looking for a numeric, but you can try to design your INPUT prompts to make it clear what you want.
When designing a program you should try to take into account run-time errors and build safety nets from the start. Often extensive program testing does not reveal all the run-time errors, and it is inconvenient to have the phone ring at 3:00 am and hear an upset user yelling that he lost all his accounting work and there is a "division by zero" error on the screen.
Logic errors are the most difficult to find and repair. BASIC cannot tell when you have a poorly designed program, so it cannot point to the error. There is no substitute for a carefully designed program but there are a few standard techniques that you can use to help you track down the problem.
Desktop Debugging: sit down somewhere far away from computers with a piece of paper and a pencil and "play computer". Go through the program line by line and do what the computer would do. Keep track of the contents of all variables on a piece of paper.
Add PRINT statements: insert print statements in key places in your program that print the contents of important variables. With this technique, you have BASIC do all the work of keeping track of the variables. You can identify the section of code that is causing problems and add even more PRINTs to it to zero in on the problem.
100 PRINT "Calculate monthly compounded interest ";
110 PRINT "for a savings account"
120 INPUT "Enter principle deposit"; P
130 INPUT "Enter length deposit in years"; Y
140 INPUT "Enter the Interest Rate in %"; I
150 LET MONTHS = Y * 12
160 LET I = I / 100
170 FOR I = 1 TO MONTHS
180 LET P = P + (P * I)
190 NEXT I
200 PRINT USING "After ## years you will have $$#####.##",Y,P
210 END
RUN [RETURN]
NONAME 1-FEB-1991 13:35
Calculate monthly compounded interest for a savings account
Enter principle deposit? 50 [Return]
Enter length deposit in years? 3 [Return]
Enter the Interest Rate in %? 6 [Return]
%BAS-F-FLOPIOERR, Floating point error or overflow
%BAS-I-FROLINMOD, from line number 180 in module INTEREST
Ready
This is a run-time error message that indicates that a floating point error or overflow occurred while executing line 180 of the program. In this case the error is an overflow, and it is indicated that the variable P is incapable of storing the result of the LET statement. At this point you should check the program over again (especially line 180 and variables associated with it) and see if the error is obvious.
Try adding PRINT statements to track the progress of the variables in the program.
100 PRINT "Calculate monthly compounded interest ";
110 PRINT "for a savings account"
120 INPUT "Enter principle deposit"; P
130 INPUT "Enter length deposit in years"; Y
140 INPUT "Enter the Yearly Interest Rate in %"; I
145 PRINT "Inputs: P="; P; " Y="; Y; " I=";I
150 LET MONTHS = Y * 12
160 LET I = I / 100
170 FOR I = 1 TO MONTHS
180 LET P = P + (P * I)
185 PRINT "After Month"; I; ":"; " P="; P, "I="; I
190 NEXT I
200 PRINT USING "After ## years you will have $$######.##",Y,P
210 END
RUN [RETURN]
NONAME 1-FEB-1991 13:35
Calculate monthly compounded interest for a savings account
Enter principle deposit? 50 [Return]
Enter length deposit in years? 3 [Return]
Enter the Interest Rate in %? 6 [Return]
Inputs: P= 50 Y= 3 I= 6
After Month 1 : P= 100 I= 1
After Month 2 : P= 300 I= 2
After Month 3 : P= 1200 I= 3
After Month 4 : P= 6000 I= 4
After Month 5 : P= 36000 I= 5
After Month 6 : P= 252000 I= 6
.
.
.
After Month 31: P= .131565E+38 I= 31
%BAS-F-FLOPIOERR, Floating point error or overflow
.
%BAS-I-FROLINMOD,from line number 170 in module INTEREST
Ready
A quick examination of these numbers shows that the Principle is going up very rapidly leading to a number so large that it must be displayed with exponential notation, and eventually becomes so huge that it overflows. You may also notice that the Interest Rate variable I is very large for a rate that should be constant at 10/100. In fact, I is varying suspiciously like a loop control variable. At this point you should see that this program makes the fatal mistake of using the variable I for both the interest rate and the loop control variable for the FOR loop. Fix the problem by renaming the loop control and run it again:
100 PRINT "Calculate monthly compounded interest ";
110 PRINT "for a savings account"
120 INPUT "Enter principle deposit"; P
130 INPUT "Enter length deposit in years"; Y
140 INPUT "Enter the Yearly Interest Rate in %"; I
145 PRINT "Inputs: P="; P; " Y="; Y; " I="; I
150 LET MONTHS = Y * 12
160 LET I = I / 100
170 FOR COUNTER = 1 TO MONTHS
180 LET P = P + (P * I)
185 PRINT "After Month"; COUNTER; ":"; " P="; P, "I=";I
190 NEXT COUNTER
200 PRINT USING "After ## years you will have $$######.##",Y,P
210 END
RUN [RETURN]
NONAME 1-FEB-1991 13:35
Calculate monthly compounded interest for a savings account
Enter principle deposit? 50 [Return]
Enter length deposit in years? 3 [Return]
Enter the Interest Rate in %? 6 [Return]
Inputs: P= 50 Y= 3 I= 6
After Month 1 : P= 53 I= .06
After Month 2 : P= 56.18 I= .06
After Month 3 : P= 59.5508 I= .06
After Month 4 : P= 63.1238 I= .06
After Month 5 : P= 66.9113 I= .06
After Month 6 : P= 70.926 I= .06
After Month 7 : P= 75.1815 I= .06
After Month 8 : P= 79.6924 I= .06
After Month 9 : P= 84.4739 I= .06
After Month 10 : P= 89.5424 I= .06
After Month 11 : P= 94.9149 I= .06
.
.
.
After Month 36 : P= 407.363 I= .06
After 3 years you will have $407.36
Ready
Even the most optimistic programmer would realize that it is unlikely that in three years, fifty dollars could be compounded to over four hundred dollars at 6% interest. The program now completes it's RUN normally and gives results, but the results are wrong. A logic error is lurking somewhere in the code. At this point check to make sure you understand the problem of compound interest. Check your implementation of the formula for compound interest, and take a close look at the output from your program RUN. The problem states that interest is to be compounded monthly and the program does a calculation for each month but each month it uses 6% (.06) as the interest rate. This is the yearly, not the monthly rate. The above output is a result of an interest rate of .06 * 12 or 72% yearly interest. Repair the problem by dividing the yearly interest rate by 12 to get the monthly rate.
100 PRINT "Calculate monthly compounded interest ";
110 PRINT "for a savings account"
120 INPUT "Enter principle deposit"; P
130 INPUT "Enter length of deposit in years"; Y
140 INPUT "Enter the Yearly Interest Rate in %"; I
145 PRINT "Inputs: P="; P; " Y="; Y; " I=";I
150 LET MONTHS = Y * 12
160 LET I = I / 100
165 LET I = I / 12
170 FOR COUNTER = 1 TO MONTHS
180 LET P = P + (P * I)
185 PRINT "After Month"; COUNTER; ":"; " P="; P, "I=";I
190 NEXT COUNTER
200 PRINT USING "After ## years you will have $$######.##",Y,P
210 END
RUN [RETURN]
6-2-DEBUG 1-FEB-1991 03:35
Calculate monthly compounded interest for a savings account
Enter principle deposit? 50 [Return]
Enter length deposit in years? 3 [Return]
Enter the Interest Rate in %? 6 [Return]
Inputs: P= 50 Y= 3 I= 6
After Month 1 : P= 50.25 I= .005
After Month 2 : P= 50.5013 I= .005
After Month 3 : P= 50.7538 I= .005
After Month 4 : P= 51.0075 I= .005
After Month 5 : P= 51.2626 I= .005
After Month 6 : P= 51.5189 I= .005
After Month 7 : P= 51.7765 I= .005
After Month 8 : P= 52.0354 I= .005
After Month 9 : P= 52.2955 I= .005
After Month 10 : P= 52.557 I= .005
.
.
.
After Month 36 : P= 59.834 I= .005
After 3 years you will have $59.83
Ready
$9.83 interest on fifty dollars over 3 years at 6% yearly interest compounded monthly seems reasonable. Test the program with more inputs, and when you are convinced that it works, take out your debugging PRINT statements.
Both the VMS operating system and the BASIC environment use system messages to inform you of the status of commands you enter. System messages can be cryptic, but contain important information to make using the system and debugging your programs easier. System messages should not be ignored.
There are three main types of system messages:
* informational
* warning
* error.
All system messages have the following format:
%facility-L-identification, description
Where:
facility * Is the name of the facility that produced the message (i.e. BASIC or BAS for the BASIC environment)
L * Is a one letter code indicating the type of message. The possibilities are as follows:
I - Informational, nothing is wrong; this message simply contains information to tell you what is happening.
S - Success; it worked; these messages are usually suppressed (who wants to see a message every time they do something right?).
W - Warning; warns you of possible problems.
E - Error; it didn't work - what ever was happening didn't work
F - Severe (Fatal) Error; it didn't work and in fact probably terminated execution.
identification * Is an abbreviation for the message and is usually impossible of which to make much sense.
description * Is a short English description of the message.
Error messages from BASIC are of two main types, RUN_TIME and COMPILE_TIME. Here are some examples of messages and what they mean.
Ready
10 PRINT "HELLO [Return]
10 PRINT "HELLO
..... ........1
%BASIC-E-UNTSTRLIT, 1: unterminated string literal
A program statement was entered that contains a syntax error. BASIC produces an Error message as soon as the programmer hit the [Return] key. Note the number 1 that points to the quote and the error text reads "unterminated string literal". BASIC is trying to tell you that you have an open quote but no close quote around the string HELLO.
You could obtain more information on what exactly the error message is by using the BASIC HELP command (see "Help in BASIC" in The BASIC Environment). To get help on an error you must specify whether the error was a syntax error (COMP) or a run-time error (RUN) and the Identification or the error. In this case the HELP command would be:
HELP COMP UNTSTRLIT [Return]
Compile_time_errors
UNTSTRLIT
ERROR - The program contains an improperly terminated string literal; for example, "ABC , "ABC', and 'ABC" are all improperly terminated. Use the same type of quotation mark (either double or single) for the beginning and ending string delimiters.
10 RETURN
20 END
RUN [RETURN]
NONAME 1-FEB-1991 13:50
%BAS-F-RETWITGOS, RETURN without GOSUB
-BAS-I-FROLINMOD, From line 10 in module NONAME
Ready
Basic is unhappy when the first thing it encounters when trying to RUN the program is a RETURN statement. Since no GOSUB was executed, BASIC has no idea where to RETURN to so it generates a run-time error. To get more HELP on this error use the following command:
HELP RUN RETWITGOS [RETURN]
Run_time_errors
RETWITGOS
RETURN without GOSUB (ERR=72)
The program executes a RETURN statement before a GOSUB. Check program logic to make sure that RETURN statements are executed only in subroutines, or remove the RETURN statement. This error cannot be trapped with a VAX BASIC error handler.
Ready
Tables require two subscripts (indexes) to specify a single cell. The terms row and column are used to differentiate the two subscripts. The row and column are separated by a comma and both are contained within parenthesis. A table named A that is 2 by 3 would be declared with a dimension:
DIM A(2, 3)
The array could be pictured like this(column zero and row zero are typically not used):
Using a two-dimensional array requires the use of nested FOR/NEXT loops (see "Relational Expressions" in "Selection" in Programming in BASIC) to generate the subscript values.
To further illustrate two-dimensional array processing, suppose a small hotel has four rooms and the owner would like to keep track of the number of beds, tables, and chairs in each room. This information can be represented in a 4 by 3 two-dimensional array using the rows to represent the different rooms and column 1 representing bed, column 2 representing tables and column 3 representing chairs.100 DIM A(2, 3)
110 FOR ROW = 1 TO 2
120 FOR COLUMN = 1 TO 3
130 READ A(ROW, COLUMN)
140 PRINT ROW, COLUMN, A(ROW, COLUMN)
150 NEXT COLUMN
160 NEXT ROW
170 DATA 99, 98, 97
180 DATA 96, 95, 94
190 END
RUN
NONAME 1-FEB-1991 12:49
1 1 99
1 2 98
1 3 97
2 1 96
2 2 95
2 3 94
Ready
Line 100: Dimension an array named A that has two dimensions; 2 rows and 3 columns
Line 110: Start of the loop that steps through the row numbers (from 1 to 2). Could be read "FOR each row in the table"
Line 120: Start of the loop that steps through the column numbers (from 1 to 3). Could be read "FOR each column in the current row"
Line 130: Get a value from data for the current cell of the 2-d array (as indicated by the row and column values).
Line 140: Print the current row and column number and the contents of the array cell with those subscripts
Line 150: End of inner loop (columns)
Line 160: End of outer loop (rows)
Line 170-180: Data statements
Line 190: END
100 DIM HOTEL(4, 3)
110 !
120 ! Load data values into the array
130 !
140 FOR ROOM = 1 to 4
150 FOR COLUMN = 1 TO 3
160 READ HOTEL(ROOM, COLUMN)
170 NEXT COLUMN
180 NEXT ROOM
190 !
200 ! Total number of pieces of furniture in the hotel and
210 ! print array contents while we are going through the
220 ! whole thing anyway
230 !
240 TOTAL = 0
250 PRINT ,"beds", "tables", "chairs"
260 FOR ROOM = 1 TO 4
270 PRINT "ROOM"; ROOM,
280 FOR COLUMN = 1 TO 3
290 PRINT HOTEL(ROOM, COLUMN),
300 LET TOTAL = TOTAL + HOTEL(ROOM, COLUMN)
310 NEXT COLUMN
320 PRINT
330 NEXT ROOM
340 PRINT "The hotel has"; TOTAL; " pieces of furniture"
350 !
360 ! Total pieces of furniture in room number 2 (row 2)
370 !
380 TOTAL = 0
390 ROOM = 2
400 FOR COLUMN = 1 TO 3
410 LET TOTAL = TOTAL + HOTEL(ROOM, COLUMN)
420 NEXT COLUMN
430 PRINT "Room number 2 has"; TOTAL; " pieces of furniture"
440 !
450 ! Total number of beds in the hotel(beds are in column 1)
460 !
470 TOTAL = 0
480 COLUMN = 1
490 FOR ROOM = 1 TO 4
500 LET TOTAL = TOTAL + HOTEL(ROOM, COLUMN)
510 NEXT ROOM
520 PRINT "The hotel has"; TOTAL; " beds"
530 !
540 DATA 0, 1, 4
550 DATA 2, 2, 0
560 DATA 6, 3, 2
570 DATA 4, 2, 0
580 END
RUN
7-1-ARRAY 1-FEB-1991 12:45
beds tables chairs
ROOM 1 0 1 4
ROOM 2 2 2 0
ROOM 3 6 3 2
ROOM 4 4 2 0
The hotel has 26 pieces of furniture
Room number 2 has 4 pieces of furniture
The hotel has 12 beds
Ready
The general forms of a DEF are:
DEF function_name(argument) = expression
or
DEF function_name(argument)
statement(s)
END DEF
where:
function_name is the name you want to give your function. The function_name is traditionally preceded by the letters "fn".
argument is a "place-holder" to show where the value used as an argument actually goes in the expression.
statement(s) The expression (or statement(s)) describing the calculation that is performed.
Single-line DEFs are mainly used to make long formula and expressions easier to use in your programs. The following example uses a single-line DEF to calculate the area of a circle ([[pi]]r2):
Functions may be passed more than one argument. Multiple arguments are separated with commas.100 DEF FNAREA(RADIUS) = 3.14159 * radius ** 2
110 PRINT "The area of a circle with radius 10 is";FNAREA(10)
120 PRINT "The area of a circle with radius 1 is"; FNAREA(1)
130 LET R = 5
140 LET A = FNAREA(R)
150 PRINT "The area of a circle with radius"; R; " is"; A
160 END
RUN
7-2-FNAREA 1-FEB-1991 13:35
The area of a circle with radius 10 is 314.159
The area of a circle with radius 1 is 3.14159
The area of a circle with radius 5 is 78.5398
Ready
The multi-line DEFs are more flexible and can be used to perform the equivalent of a subroutine, in a more organized way. In order to "return" a value a multi-line DEF must assign a value to the NAME of the function.
The following multi-line function example reverses a character string:
100 DEF REVERSE$(LINE$)
110 LET TEMP$ = ""
120 FOR LOCATION = LEN(LINE$) TO 1 STEP -1
130 LET TEMP$ = TEMP$ + MID$(LINE$,LOCATION,1)
140 NEXT LOCATION
150 REVERSE$ = TEMP$
160 END DEF
170 !
180 INPUT "Enter characters & I'll reverse them(END to quit)";S$
190 WHILE S$ <> "END"
200 PRINT REVERSE$(S$)
210 INPUT "Enter characters & I'll reverse them(END to quit)";S$
220 NEXT
230 END
RUN
7-2-REVERSE 1-FEB-1991 14:36
Enter characters & I'll reverse them (END to quit)?
BACKWARDS?[Return]
?SDRAWKCAB
Enter characters & I'll reverse them (END to quit)?
is this reversed?[Return]
?desrever siht si
Enter characters &I'll reverse them (END to quit)?
wow[Return]
wow
Enter characters & I'll reverse them (END to quit)?
END[Return]
Ready
OPEN "file_name" FOR mode AS FILE #n
Where:
"file_name": * Is the name of the file you want opened. The file_name must be enclosed in quotes and may include a file extension (see "File Specifications" in "files" in Introduction to VAX/VMS).
mode: * Is one of INPUT, OUTPUT, or APPEND and is used to tell BASIC what you want to do with the file once you have it open.
Modes (all are from the "viewpoint" of the program):
For INPUT: an existing file is to be opened and data will be read from it.
For OUTPUT: create a new file so that data can be written into it. If the file does not exist it is created.
For APPEND: open an existing file and go to the end of it to allow more data to be added. If the file does not exist it is created.
#n * Is a channel number that BASIC associates with the open file and is used throughout the program when referring to the file.
The following program creates a file named MYFILE, writes a line of data on it and then closes the file.
You can verify the creation of MYFILE with the $DIR command (see "File Manipulation Commands" in "VMS System Commands" in Introduction to VAX/VMS) and even display the contents of MYFILE with the $TYPE command (see "File Manipulation Commands" in "VMS System Commands" in Introduction to VAX/VMS).100 OPEN "MYFILE" FOR OUTPUT AS FILE #1
110 LET R$ = "THIS IS A LINE FOR MYFILE"
120 PRINT #1, R$
130 CLOSE #1
140 END
Line 100: The file MYFILE is created as it doesn't previously exist and is prepared for OUTPUT. The file is now referred to as #1 (channel #1).
Line 110: Character string R$ is given a value
Line 120: A variation of the PRINT statement (see "Writing to a File" in "File Input and Output" in Advanced BASIC) is used to PRINT on the file instead of the terminal.
Line 130: The file is closed.
Line 140: END
CLOSE #n
Where:
n * Is an open channel.
You can close several channels by separating them with commas. You should always close files when you are finished using them, and certainly before the end of the program. Once a file has been closed it can be reopened with another mode, to facilitate reading and writing to the same file.
In the previous example, the statement:
130 CLOSE #1
closes 'MYFILE' which was opened on channel 1. If you have files open on channels 2, 4, and 6 then the statement
100 CLOSE #2, #4, #6
will close those files.
PRINT #n, list_of_data
where:
#n * Is the channel number of a file that has been previously OPENed (see "Input and Print" in Programming in BASIC)
list_of_data * Is the same as the standard PRINT statement. If you use the channel number zero (0), the list_of_data will be printed on the terminal instead of a file (this can be useful for debugging). A comma separates the channel number from the list_of_data.
Here is a sample program that creates a file with a class list of student numbers and names.
Note that when the program is RUN there is NO OUTPUT to the terminal. Everything is directed to the CLASS file.100 OPEN "CLASS" FOR OUTPUT AS FILE #1
110 PRINT #1, "CLASS LIST"
120 PRINT #1, "FALL 1981"
130 PRINT #1
140 PRINT #1, "NUMBER", "NAME"
150 READ N, N$
160 WHILE N$ <> "DUMMY"
170 PRINT #1, N, N$
180 READ N, N$
190 NEXT
200 CLOSE #1
210 DATA 122516, "BROWN, J"
220 DATA 233124, "SMITH, M"
230 DATA 241789, "JONES, B"
240 DATA 351812, "HALTON, M"
250 DATA 491684, "MARKOVICH, S"
260 DATA 0, "DUMMY"
270 END
RUN
NONAME 1-FEB-1991 13:35
Ready
Line 100: The file CLASS is created and readied for output. It will be referred to as channel #1
Line 110-140: Puts titles in the CLASS file.
Line 150: Get the first student number and name from data
Line 160: Loop continues until the name DUMMY is encountered indicating the end of data.
Line 170: PRINTs the student number and name last READ from data to channel #1 (CLASS file)
Line 180: Get the next student number and name
Line 190: Marks the end of the WHILE loop
Line 200: The program is finished with channel #1 so close it
Line 210-260: DATA statements
Line 270: END
When this program is run the data will appear in the file as follows:
CLASS LIST
FALL 1981
NUMBER NAME
122516 BROWN,J
233124 SMITH,M
241789 JONES,B
351812 HALTON,M
491684 MARKOVICH,S
INPUT #n, variable_list
where:
#n is the channel number of a file that has been previously OPENed (see "Print" in "Input and Print" in Programming in BASIC),
variable_list is the same as the standard INPUT statement. A comma separates the channel number from the list_of_data.
Because the INPUT # statement reads data in the file in the same manner as the INPUT statement, data placed in the file must be separated by commas. This means that when the file is created you must take care to place commas between the data item. Consider the following:
100 PRINT #3, N; ","; N$
110 INPUT #1, X, A$
Line 10 is a line which writes data to a file. Line 20 is a line which reads data from a file. Both lines contain the same number of variables in the same order and type. The data items written to the file include a comma in quotes.
100 OPEN "NAMES" FOR OUTPUT AS FILE #3110 READ N, N$
120 WHILE N$ <> "DUMMY"
130 PRINT #3, N; ","; N$
140 READ N, N$
150 NEXT
160 PRINT #3, N; ","; N$
170 DATA 12, 'JONES'
180 DATA 13, 'BROWN'
190 DATA 29, 'SMITH'
200 DATA 99, 'DUMMY'
210 CLOSE #3
220 END
RUN
NONAME 1-FEB-1991 13:35
Ready
Line 100: Create a new file called NAMES and get it ready to be written to channel number 3
Line 110: Get the first number and name from data
Line 120: Loop until a name of DUMMY is read
Line 130: Write the current number and name to the NAMES file with a separating comma so that we can get INPUT from the file later.
Line 140: Get the next number and name
Line 150: Marks the end of the loop
Line 160: Writes the "DUMMY" marker to the file so that getting INPUT from the file will be easier later
Line 170-200: Data
Line 210: Close channel #1
Line 220: END
100 OPEN "NAMES" FOR INPUT AS FILE #1
110 INPUT #1, X, A$
120 WHILE A$ <> "DUMMY"
130 PRINT X, A$
140 INPUT #1, X, A$
150 NEXT
160 CLOSE #1
170 END
RUN
NONAME 1-FEB-1991 8:54
12 JONES
13 BROWN
29 SMITH
Ready
Line 100: OPEN the existing NAMES file created in the above previous program.
Line 110: Get the first number and name from the file (without the separating comma, this would not work)
Line 120: Loop continues until the name is DUMMY
Line 130: PRINT the current number and name on the terminal
Line 140: Get the next number and name from the NAMES file
Line 150: Marks the end of the loop
Line 160: Close channel 3
Line 170: END
Make the heading section of your program a remark section containing the following pieces of identification and information:
AUTHOR: name and student number
DATE: current date
TITLE: program name (assignment number)
PURPOSE: purpose of program (one sentence)
SYSTEM: the make and model of the computer that you used to create the program, and the version of BASIC you are running
ALGORITHM: description of method for solving problem
VARIABLES: list of variables and their uses (alphabetical order).
* Documentation.
* To identify each module of the program..
* To identify each subroutine.
* The subprogram modules should have as a heading:
* a title,
* an algorithm,
* a list of variables.
* To make in-code comments where necessary.
* Indent the body of all loops, and multi-line selection statements. For example:
100 FOR I = 1 TO 5
110 FOR J = 1 TO 4
120 SELECT 1
130 CASE 1
140 statements
150 CASE 2
160 statements
170 CASE ELSE
180 statements
190 NEXT J
200 NEXT I
* Although BASIC allows you to use the \ and put more than one statement on a line, do not use it.
* The point where the listing stops and the run starts should be clearly marked.
* Include only the listings and test runs in your assignment. The marker does not want to see your logins, logouts and all versions of your program.
* In general, when using the INPUT statement, use an explicit prompt for any data your program needs, e.g.
10 INPUT "ENTER GRADE";G
* Use STOP statements in the program only while debugging, not in the final listing.
* Design your programs so that your logic flow is clear and easy to follow. (For a discussion of structured programming, see your textbook). Take advantage of VMS-BASIC's powerful structured language features like the WHILE loop and the SELECT statement. Avoid use of GOTOs.
Problem:
Write a BASIC program which will accept any positive number from the terminal and print its square root. An input of zero will end the program. Submit your flowchart, as well as the BASIC program and test run(s).
Solution includes:
* class cover sheet (you can copy it from NEWS account)
* flowchart
* program listing
* program test run(s)
LISTAPPENDIX-ROOT 18-MAR-1987 9:59
100 REM *************************************************
110 REM * *
120 REM * Author: John Doe Student Number: 123456789 *
130 REM * *
140 REM * Title: Class Assignment One *
150 REM * Date: March 19, 1987 *
160 REM * System:Developed on a VAX 6320 with VAX-BASIC *
170 REM * *
180 REM * Purpose:Find the square root of input numbers *
190 REM * until a zero (0) is encountered *
200 REM * *
210 REM * Algorithm: *
220 REM * 1. Get a number *
230 REM * 2. If the number is 0, perform step 7. *
240 REM * 3. If the number is negative, output an *
250 REM * error message and perform step 1. *
260 REM * 4. Compute the square root of the number *
270 REM * 5. Output the square root of the number *
280 REM * 6. Perform step 1. *
290 REM * 7. Stop. *
300 REM * *
310 REM * Variables: *
320 REM * NUMBER - the largest grade encountered *
330 REM * ROOT - the square root of NUMBER *
340 REM * *
350 REM *************************************************
360 !
370 ! Output User Instructions
380 !
390 PRINT TAB(17); "Square Root Program"
400 PRINT
410 PRINT "Enter any positive number and its square";
420 PRINT " root will be printed."
430 PRINT TAB(10); "Enter zero (0) to stop the";
440 PRINT " program."
450 PRINT
460 !
470 ! Get the first number from the user
480 !
490 INPUT "Enter a number (0 to quit)"; NUMBER
500 !
510 ! Loop continues as long as the user keeps entering non-520 ! zero numbers.
530 ! If the number is negative, an error message is
540 ! printed; if the number is positive, the square root is 550 ! found and printed. In either case the user is
560 ! prompted for another number.
570 !
580 WHILE NUMBER <> 0
590 IF NUMBER < 0 THEN
PRINT "CANNOT FIND THE ROOT OF A NEGATIVE NUMBER."
PRINT "Please enter positive numbers only."
ELSE
LET ROOT = SQR(NUMBER)
PRINT "The square root is"; ROOT
END IF
600 PRINT
610 INPUT "Enter a number (0 to quit)"; NUMBER
620 NEXT
630 !
640 ! End of program
650 !
660 PRINT
670 PRINT "End of program -- have a nice day"
680 END
Ready
RUN
APPENDIX-ROOT 18-MAR-1987 10:00
Square Root Program
Enter any positive number and its square root will be printed.
Enter zero (0) to stop the program.
Enter a number (0 to quit)? 9
The square root is 3
Enter a number (0 to quit)? 144
The square root is 12
Enter a number (0 to quit)? 2
The square root is 1.41421
Enter a number (0 to quit)? 0
End of program -- have a nice day
Ready
RUN
APPENDIX-ROOT 18-MAR-1987 10:01
Square Root Program
Enter any positive number and its square root will be printed.
Enter zero (0) to stop the program.
Enter a number (0 to quit)? 123456
The square root is 351.363
Enter a number (0 to quit)? -10
CANNOT FIND THE ROOT OF A NEGATIVE NUMBER.
Please enter positive numbers only.
Enter a number (0 to quit)? 0
End of program -- have a nice day.
Ready
The following section provides information on several different BASIC error messages. This information is generalized for a standard BASIC compiler, SO THE MEENA BASIC ERROR MESSAGES MAY NOT BE WORDED THE SAME WAY. If you find a message that you have problems with, check these errors for a similar message.
Types of errors:
- Logic (A < B instead of A > B)
- Syntax (typographical errors)
- Run time (errors which do not appear until the program is run)
- Style (failure to indent, comment, and do on)
NOTE: Some errors may fall into more than one category
?Can't find file or account
Attempt to access a file or account that does not exist.
%Data Format error
An attempt to READ or INPUT improper data.
Example: trying to read a character into a numeric variable.
?End of file on device
Missing END statement.
?File exists -
RENAME/REPLACE
Attempt to SAVE a file which has already been SAVED.
?FNEND without DEF
The end of a function definition was found without a beginning.
?FOR without NEXT
FOR statement found without a corresponding NEXT.
?Illegal line numbers
A line number less than 1 or greater than 32767 was used, or no line number at all.
Example: you might have typed a letter "o" instead of the number zero.
?Illegal mode mixing
String and numeric operations have been combined.
?Illegal number
Number is greater than 32767 or less than -32768.
?Illegal symbol
An unrecognized character was encountered.
?Illegal verb
The verb (action) portion of statement is unrecognizable.
?Line too long
Line length is greater than 255 characters.
?Matrix dimension error
Attempt to have more than a 2 dimensional matrix.
?Matrix or Array too big
A matrix or array was DIMed too big for the system.
?Modifier error
A FOR, WHILE, UNTIL, IF or UNLESS statement has been incorrectly used.
?NEXT without FOR
A NEXT statement was encountered without a corresponding FOR statement.
?Out of data
Attempt to READ data after DATA list is exhausted. All items of data on a line must be separated by a comma except for the last item, which has nothing after it.
?Protection violation
An attempt to access a file by an unauthorized user was made.
?RETURN without GOSUB
A RETURN statement was encountered without a corresponding GOSUB.
?Statement not found
Reference was made to a non-existent line number.
?Subscript out of range
Attempt to access an array element beyond the number in the DIM statement.
?Syntax error
The statement typed in is incorrect.
?Too few arguments
A function was called with more arguments than in the definition.
?Too many arguments
A user defined function may have up to 5 arguments.
?What?
Command could not be processed, computer could make"no sense" of its line of code
To find and correct logic errors there are two main methods:
1. STOP statements:
Insert stop statements in various places in your program where you feel there is a problem.
EXAMPLE:
100 STOP
Your program will pause temporarily so that you can check the value of variables.
EXAMPLE:
PRINT A$,A,B,C [RETURN]
HERBIE SWARTZ 25 8 -354
If you find a variable which is incorrect but wish to continue testing the rest of the program then you can change the value of the variable and start the program running from the point where it stopped. This is done by doing the following:
LET B = 449 [RETURN] This will change the value temporarily
CONT [RETURN]
The error can be noted so that you remember it but you can also see if the rest of the program works before you make any changes.
2. PRINT statements
Print statements can also be used for debugging. By placing PRINT statements in different places in your program there are many things you can find out. You can find out the flow of the program. You can find out the value of variables during the execution of a program, and so on.
EXAMPLE:
100 PRINT "AT LINE 100"
This will tell you every time that line 100 is executed. If you place this type of statement in critical places in your program such as where an IF THEN statement goes to and right after the IF THEN statements the flow of the program can be determined.
Also the values of variables can be found out during the execution of a program. If you are having trouble finding where a variable's value is being changed improperly then by having PRINT statements in your program at the points where it is being changed you can find out its value at those places.
EXAMPLE:
120 POINT "THE VALUE OF A IS";A
A way of insuring that you will be able to add these statements is by doing the following:
INCORRECT CORRECT 100 IF X > Y GOTO 150 100 IF X > Y GOTO 150 110 T = X 110 T = X ... ... ... ... 150 Y = T 150 REM CAN PUT A STOP OR PRINT STATEMENT HERE 160 Y = T
By using the REM statement in this fashion you will be able to add STOP or PRINT statements in your program without any difficulty.
The sample questions in this section include general computer science questions at an introductory level, as well as specific problems in the Basic programming language.
PART 1 True or False
1. ( ) Third generation computers utilized high-level computer languages.
2. ( ) The first consideration in determining the suitability of an application for a computerized solution is whether the problem is justifiable.
3. ( ) Input and output can not be considered as functions of data processing cycle.
4. ( ) Peopleware is an element of a computer system.
5. ( ) The laser printer is an example of dot matrix printers.
6. ( ) A terminal is only an input device.
7. ( ) Serial computers are generally faster than parallel computers are.
8. ( ) RAM is read only memory too.
9. ( ) An operating system is an example of application software programs.
10. ( ) Floppy disks can be accessed sequentially or directly.
11. ( ) The set of programs used to set up and maintain a database is called a database management system.
12. ( ) The expressions 10+10*2 and (10+10)*2 evaluate to the same value in BASIC.
13. ( ) A systems analyst's job is to write the programs necessary for the needs of the users.
14. ( ) In general, internal processing is faster than input/ output.
15. ( ) With virtual storage the computer can run a program that requires more primary storage than is available.
16. ( ) In a flowchart, the processing symbol is a rectangle.
17. ( ) Increased use of the computer has brought about many new problems.
18. ( ) An instruction is made up of an operation code and one or more operands.
19. ( ) The system's life cycle consists of birth, growth, full development, deterioration, and death. But information systems do not.
20. ( ) One problem with spreadsheets is that mathematical formulas are difficult to enter.
PART 2 Multiple Choice
Circle only ONE correct or best answer for each of the following:
The fourth generation of computers began in:
a. 1980
b. 1970
c. 1965
d. none of the above
Which of the following is not a microcomputer?
a. Apple Macintosh
b. Apple II
c. IBM PC
d. VAX 8600
The is the code used to represent numbers electronically.
a. decimal system
b. binary system
c. octal system
d. none of the above
Which of the following is not a major part of the CPU?
a. control unit
b. arithmetic unit
c. primary storage
d. I/O buffer
A major disadvantage of semiconductor memory is:
a. it costs much more than core memory
b. it is unreliable for holding important information
c. it is volatile
d. it takes a trained professional to repair it.
K is short for "kilo" and in computer terms implies:
a. 1,000 bits or bytes
b. 1,042 bits or bytes
c. 1,024 bits or bytes
d. 1,000,000 bits or bytes
Which of the following is not a secondary storage device?
a. magnetic disk
b. magnetic tape
c. 3 1/2 inch floppy disk
d. storage in a terminal
The network links each device in the network to a
central control unit.
a. ring
b. local area
c. star
d. bus
A set of logically related files is classified as:
a. a record
b. an indexed file
c. a directory
d. a database
Which of the following is considered as a stage of preliminary
investigation?
a. purchase of new equipment
b. fact finding
c. data presentation
d. program writing
A system in which I/O devices and auxiliary equipment are not
under the direct control of the computer is classified as:
a. an independent system
b. a shared system
c. an offline system
d. a time-sharing system
A multiplexor is designed to:
a. allow one terminal to be accessed by several lines
b. connect a modem to a high-speed line
c. allow one high-speed line to serve several low-speed lines
d. speed up data transmission
Each location in primary storage is assigned a unique:
a. value
b. name
c. field
d. address
One byte can hold how many different integer values?
a. 8
b. 16
c. 128
d. 256
New products can be designed with the help of:
a. CAI
b. CAD/CAM
c. UPC
d. IBM
The real language of the computer is:
a. COBOL
b. BASIC
c. machine language
d. all of the above
A sequence of instructions designed to perform a specific task
is called a:
a. computer operation
b. program
c. hardware device
d. all of the above
e. none of the above
Which of the following is not an input device?
a. card reader
b. disk drive
c. laser printer
d. magnetic drum
e. magnetic ink character reader
In primary storage, numbers are stored in:
a. decimal form
b. binary form
c. hexadecimal form
d. bittal form
e. whatever form the program calls for
The size of a field of data:
a. is determined by the hardware
b. will always be the same size
c. may vary in size only when grouped in a record
d. is determined by the data it is to contain
e. none of the above
The sectors on your 3 1/2 inch micro, floppy diskette are
numbered from:
a. 00-49
b. 00-79
c. 0-9
d. 000-199
e. 00-99
In a relational database, data are organized into:
a. nodes
b. one-dimensional lists
c. parents and nodes
d. two-dimensional tables
e. queues
During word processing, as words are entered via the keyboard,
they:
a. are automatically checked for spelling errors
b. are automatically saved on disk
c. appear on the screen
d. are immediately printed
e. all of the above
A group of related elements and procedures working together
to accomplish a task is referred to as:
a. a procedure
b. a system
c. a feasibility study
d. a program
e. a loop
PART 3 Definition
Provide a brief definition or description for the following terms:
CRT:
The Central Processing Unit:
A computer word:
Binary numbers system:
Electronic mail:
Machine language:
Magnetic bubble storage:
PART 4 Short answer
Discuss some of the reasons for using subroutines in programs.
Give the five phases of a systems project.
Explain the difference between a GOTO and a GOSUB in BASIC.
Show by example that you know how bubble sort works:
Explain the four basic functions of WORKS program.
Answer each of the following:
a) Convert the following binary number to its decimal and
hexadecimal equivalents:
11001112
b) The ASCII code for "c" is 9910. What is the ASCII code for "h"?
c) What is meant by random or direct access?
d) Make a sketch of a bus LAN (Local Area Network) labelling all the component parts clearly.
e) Discuss briefly the systems analysts' main tasks during systems design and systems development.
PART 5 Basic
Show the output of the following programs, if any.
10 read x,y,z
20 let z=x+y
30 let y=x+z
40 let z=y+x
50 read x,y
55 print x,y,z
60 data 1,2,3,5,5,6
10 for i=1 to 5
20 let a$="i+1"
30 print a$,i
40 next i
50 end
10 let a=1
20 let b=2
30 let c=4
40 let d=8
50 print a+c/b-d
60 print d/c+a*(a+b)
70 end
10 let A$="This final seems weird"
20 print left$(A$,4), right$(A$,2), mid$(A$,10,3)
30 print x
40 end
Find and correct the errors in the following examples of BASIC code:
a) 10 A = 10
20 N$ = 30
30 PRINT A, N$
40 PRINT (A + N$)
b) 10 FOR I = 1 TO 20
20 READ A(I)
30 NEXT I
.
.
.
100 DATA 1, 2, 3, 4, 5, 6
110 DATA 7, 8, 9, 10, 11, 12
120 END
PART 6 Programming
Write a program (NO FLOWCHART or REMs) that will accept 10 English words from the terminal and place them into a one-dimensional array. The program will not accept DUPLICATE words. All words are in lower case.
The program will check each word to make sure it has not been entered before. If it is a duplicate, the program should return to the original input line to get a replacement word. This replacement word will also be checked for duplication.
This program should have friendly prompts and messages for the user. When 10 unique words are entered in an array, the program should output the contents of the array to show the user what it has received.
Write a BASIC program which will input a list of names, phone numbers and addresses from DATA statements into arrays. Write the program so that it will handle up to 100 items of each type and use the special name of "NONAME" for the end of the data.
After the data has been READ, sort the arrays by the name and print a list of names, phone numbers and addresses to the screen.
Once the arrays have been sorted and the listing printed, allow the users to search for a particular name (exact match only) and print out the name, phone number and address if it is found, or an error message if it isn't. Use the fact that the name array is sorted to make your search more efficient.
Assume that you have the following DATA statements for your program:
9000 DATA "ROGER RABBIT", "555-1234", "A HOLE, SOMEWHERE IN NEW YORK
9100 DATA "ET", "1-800-7GO-HOME", A PLANET, SOMEWHERE . . .
9200 DATA "M. MOUSE", "123-4567", "WALLY WORLD"
9300 DATA "D. DUCK", "123-4568", NEXT DOOR TO M. MOUSE"
9400 DATA "NONAME"
No comments or flowcharts are required.
a) Write a BASIC subprogram that will produce the PAYMENT for a specific LOAN, MONTHLY INTEREST, and TERM where:
Your subprogram should start on line 1000. No comments orflowchart are necessary.
b) Using the subprogram written in part a), (whether you have
one or not, assume that it works), write a BASIC program to:
i) Input the LOAN and YEARLY INTEREST
ii) Select one of A) to produce a list of repayment
amounts for various periods
B) to determine if the salary is
high enough to repay the loan
C) quit
iii) A) If "to produce a list" were chosen:
Input the NUMBER-MONTHS
If NUMBER-MONTHS is not between 1 and 20
print an error and return to step ii)
Otherwise, print out a formatted table of
TERM and PAYMENT for each of 1 to
NUMBER-MONTH terms.
B) If "to determine if salary is high enough" is
chosen:
Input SALARY and TERM
Output SALARY is high enough if SALARY > 3
* PAYMENT
C) If "quit" is chosen, then END
iv) Return to ii)
No flowchart and no comments are required.