Make your own free website on Tripod.com

SECTION 4

[continue/next section] [MAIN/Introduction] [table of contents]

4. Advanced Basic Programming


TABLE OF CONTENTS

4.1 COMPUTER DECISIONS - The IF-THEN Statement

4.1.1 Using the Colon

4.2 LOOPS - The FOR-NEXT Command

4.2.1 Empty Loops - Inserting Delays in a Program
4.2.2 The STEP Command

4.3 INPUTTING DATA

4.3.1 The INPUT Command
4.3.1.1 Assigning a value to a variable
4.3.1.2 Prompt Messages
4.3.2 The GET Command
4.3.3 Sample Program
4.3.4 The READ-DATA Commands
4.3.5 The RESTORE Command
4.3.5.1 Assigning values to string variables
4.3.6 Using Arrays
4.3.6.1 Subscripted Variables
4.3.6.2 Dimensioning Arrays
4.3.6.3 Sample Program

4.4 PROGRAMMING SUBROUTINES

4.4.1 The GOSUB-RETURN Commands
4.4.2 The ON GOTO/GOSUB Commands

4.5 USING MEMORY LOCATION

4.5.1 Using PEEK and POKE for RAM Access
4.5.1.1 Using PEEK
4.5.1.2 Using POKE

4.6 BASIC FUNCTIONS

4.6.1 What is a Function?
4.6.2 The INTEGER Function (INT)
4.6.3 Generating Random Numbers - The RND Function
4.6.4 The ASC and CHR$ Functions
4.6.5 Converting Strings and Numbers
4.6.5.1 The VAL Function
4.6.5.2 The STR$ Function
4.6.6 The Square Root Function (SQR)
4.6.7 The Absolute Value Function (ABS)

4.7 THE STOP AND CONT (CONTINUE) COMMANDS

This section describes how to use a number of powerful BASIC commands, functions and programming techniques that can be used in both C128 and C64 modes.

These commands and functions allow you to program repeated actions through looping and nesting techniques; handle tables of values; branch or jump to another section of a program, and return from that section; assign varying values to a quantity - and more. Examples and sample programs show just how these BASIC concepts work and interact.

4.1 COMPUTER DECISIONS - The IF-THEN Statement

Now you know how to change the values of variables, the next step is to have the computer make decisions based on these updated values. You do this with the IF-THEN statement.

You tell the computer to execute a command only IF a condition is true (e.g. IF X=5). The command you want the computer to execute when the condition is true comes after the word THEN in the statement.

Clear your computer's memory by typing NEW and pressing {return}, then type in this program:

10 J=0
20 J=J+1
30 ? J,"COMMODORE 128"
40 IF J=5 THEN GOTO 60
50 GOTO 20
60 END

You no longer have to press the {stop} key to break out of a looping program. The IF-THEN statement tells the computer to keep printing "COMMODORE 128" and incrementing (increasing) J until J=5 is true. When an IF condition is false, the computer jumps to the next line of the program, no matter what comes after the word THEN.

Notice the END command in line 60. It is good practice to put an END statement as the last line in your program. It tells the computer where to stop executing statements.

Below is a list of comparison symbols that may be used in the IF statement and their meanings:

SYMBOL  MEANING

=       EQUALS
>       GREATER THAN
<>      NOT EQUAL TO
>=      GREATER THAN OR EQUAL TO
<=      LESS THAN OR EQUAL TO

You should be aware that these comparisons work in expected mathematical ways with numbers. There are different ways to determine if one string is greater than, less than, or equal to another. You can learn about these "string handling" functions by referring to Chapter V, Basic 7.0 Encyclopaedia.

Section 5 describes some powerful extensions of the IF-THEN concept, consisting of the BASIC 7.0 commands BEGIN, BEND and ELSE.

4.1.1 Using the Colon

A very useful tool in programming is the colon (:). You can use the colon to separate two (or more) BASIC commands on the same line.

Statements after a colon on a line will be executed in order, from left to right. In one program line you can put as many statements you can fit into 160 characters, including the line number. This is equivalent to four full screen lines in 40-column format, and two full lines in 80-column format.

This provides an excellent oppurtunity to take advantage of the THEN part of the IF-THEN statement. You can tell the computer to execute several commands when you IF statement is true.

Clear the computer's memory and type in the following progam:

10 N=1
20 IF N<5 THEN PRINT N;"LESS THAN 5":GOTO 40
30 ? N;"GREATER THAN OR EQUAL TO 5"
40 END

Now change line 10 to read N=20, and RUN the program again. Notice you can tell the computer to execute more than one statement when N is less than 5. You can put any statement(s) you want after the THEN command. Remember that the GOTO 40 will not be reached if N is true. Any command that should be followed whether or not the specified condition is met should appear on a separate line.

4.2 LOOPS - The FOR-NEXT Command

In the program used for the IF-THEN example, we made the computer print COMMODORE five times by telling it to increase or "increment" the variable J by units of one, until the value of J equalled five; then we ended the program. There is a simpler way to do this in BASIC. We can use a FOR-NEXT loop, like this:

10 FOR J=1 TO 5
20 ?J,"COMMODORE 128"
30 NEXT J
40 END

Type and RUN this program and compare the result with the result of the IF-THEN program - they are the same. In fact, the steps taken by the computer are almost identical for the two programs. The FOR-NEXT loop is a very powerful programming tool. You can specify the number of times the computer should repeat an action. Let's trace the computer's steps for the program above.

First, the computer assigns a value of 1 to the variable J. The 5 in the FOR statement tells the computer to execute all statements between the FOR statement and the NEXT statement, until J is equal to 5. In this case there is just one statement - the PRINT statement.

The computer first assigns 1 to J, it then goes on to execute the PRINT statement. When the computer reaches the NEXT J statement, J is incremented and compared with 5. If J has not exceeded 5 the computer loops back to the PRINT statement.

After five executions of this loop the value of J exceeds 5, the program drops down to the statement that comes immediately after the NEXT statement and continues from there. In this case the following statement is the END statement, so the program stops.

4.2.1 Empty Loops - Inserting Delays in a Program

Before you proceed any further, it will be helpful to understand about loops and some ways they are used to get the computer to do what you want. You can use a loop to slow down the computer (by now you have witnessed the speed with which the computer executes commands). See if you can predict what this program will do before you run it.

10 A$="COMMODORE 128"
20 FOR J=1 TO 20
30 PRINT
40 FOR K=1 TO 1500
50 NEXT K
60 PRINT A$
70 NEXT J
80 END

Did you get what you expected?

The loop contained in line 40 and 50 tells the computer to count to 1500 before executing the remainder of the program. This is known as a delay loop and is often used. Because it is inside the main loop of the program, it is called a nested loop. Nested loops can be very useful when you want the computer to perform a number of tasks in a given order, and repeat the entire sequence of commands a certain number of times.

Section 5 describes an advanced way to insert delays through the use of the new BASIC 7.0 command, SLEEP.

4.2.2 The STEP Command

You can tell the computer to increment your counter by units (e.g. 10, 0.5 or any other number). You do this by using a STEP command with the FOR statement. For example, if you want the computer to count by tens to 1000, type:

10 FOR X=0 TO 1000 STEP 10
20 ? X
30 NEXT

Notice that you do not need the X in the NEXT statement if you are only executing one loop at a time - this is discussed later in this section. Also, note that you do not have to increase (or "increment") your counter - you can decrease (or "decrement") it as well. For example, change line 10 in the program above to read:

10 FOR X=100 TO 0 STEP - 10
the computer will count backward from 100 to 0, in units of 10.

If you don't use a STEP command with a FOR statement, the computer will automatically increment the counter by units of 1.

The parts of the FOR-NEXT commands are:

FOR

  word used to indicate beginning of loop.

X

counter variable; any number variable can be used.

1

starting value; may be any number, positive, negative or zero.

TO

connects starting value to ending value.

100

ending value; may be any number, positive, negative or zero.

STEP

indicates an increment other than 1 will be used.

2

increment; can be any number, positive, negative or zero.

Section 5 describes DO/LOOP, a new, more powerful BASIC 7.0 command to perform a similar task to the STEP command.

4.3 INPUTTING DATA

4.3.1 The INPUT Command

4.3.1.1 Assigning a value to a variable

Clear the computer's memory by typing NEW and pressing {return}, and then type and RUN this program:

10 K=10
20 FOR I=1 TO K
30 ?"COMMODORE 128"
40 NEXT

In this program you can change the value of K in line 10 to make the computer execute the loop as many times as you want it to. You have to do this when you are typing in the program, before it is RUN. What if you wanted to be able to tell the computer how many times to execute the loop at the time the program is RUN?

In other words, you want to be able to change the value of the variable K each time you run the program, without having to change to program itself. We call this the ability to interact with the computer. You can have the computer ask how many times you want it to execute the loop. To do this, use the INPUT command. For example, replace line 10 in the program with:

10 INPUT K

Now when you RUN the program, the computer reponds with a ? to let you know it is waiting for you to enter what you want the value of K to be. Type 15 and press {return}. The computer will execute the loop 15 times.

4.3.1.2 Prompt Messages

You can also make the computer print a message in an INPUT statement to tell you what variable it's waiting for. Replace line 10 with:

10 INPUT"PLEASE ENTER A VALUE FOR K";K

Remember to enclose the message to be printed in quotes. This message is called a prompt. Also, notice that you must use a semicolon (;) between the ending quote marks of the prompt and the K. You may put any message you want in the prompt, but the INPUT statement must be 160 characters or less, just as any BASIC command must.

The INPUT statement can also be used with string variables. The same rules that apply for numeric variables apply for strings. Don't forget to use the {$} to identify all you string variables.

Clear you computer's memory by typing NEW and pressing {return}. Then type this program.

10 INPUT"WHAT IS YOUR NAME";NM$
20 ? "HELLO ";N$

Now RUN the program. When the computer prompts "WHAT IS YOUR NAME?", then type your name. Don't forget to press {return} after you type your name.

Once the value of a variable (numeric or string) has been inserted into a program through the use of INPUT, you can refer to it by its variable name any time in the program. Type ?N$ {return} - your computer remembers your name!

4.3.2 The GET Command

There are other BASIC commands you can use in your program to interact with the computer. One is the GET command and is similar to INPUT. To see how the GET command works, clear the computer's memory and type this program:

10 GET A$
20 IF A$="" THEN 10
30 ? A$
40 END

When you type RUN and press {return}, nothing seems to happen. The reason is that the computer is waiting for you to press a key. The GET command, in effect, tells the computer to check the keyboard and find out what character or key is being pressed. The computer is satisfied with a null character (that is, no character). This is the reason for line 20. This line tells the computer that if it gets a null character, indicated by double quotes with no space in between them, it should go back to line 10 and try to GET another character. This loop continues until you press a key. The computer then assigns the character on that key to A$.

The GET command is very important because you can use it, in effect, to program a key on your keyboard. The example below prints a message on the screen when {q} is pressed. Type the program and RUN it. The press {q} and see what happens.

10 ?"PRESS Q TO VIEW MESSAGE"
20 GET A$
30 IF A$="" THEN 20
40 IF A$="Q" THEN 60
50 GOTO 20
60 FOR I=1 TO 25
70 ? "NOW I CAN USE THE GET STATEMENT"
80 NEXT
90 END

Notice that if you try to press any key other than the {q}, the computer will not display the message, but will go back to line 20 to GET another character.

Section 5 describes how to use the GETKEY statement, which is a new and more powerful BASIC 7.0 command that can be used to perform a similar task.

4.3.3 Sample Program

Now that you know how to use the FOR-NEXT loop and the INPUT command, clear the computer's memory by typing NEW {return}, then type the following program:

10 T=0
20 INPUT"HOW MANY NUMBERS";N
30 FOR J=1 TO N
40 INPUT"PLEASE ENTER A NUMBER";X
50 T=T+X
60 NEXT
70 A=T/N
80 PRINT
90 ? "YOU HAVE";N"NUMBERS TOTALING "T
100 ? "AVERAGE = ";A
110 END

This program lets you tell the computer how many numbers you want to average. You can change the numbers every time you run the program without having to change the program itself.

Let's see what the program does, line by line:

Line 10
assigns a value of 0 to T (which will be the running total of the numbers).
Line 20
lets you determine how many numbers to average, stored in variable N.
Line 30
tells the computer to execute a loop N times.
Line 40
lets you type in the actual numbers to be averaged.
Line 50
adds each number to the running total.
Line 60
tells the computer to increment the counter (J) and loop back to line 30 while the counter (J) <= N.
Line 70
divides the total by the amount of numbers you typed in (N) after the loop has been executed N times.
Line 80
prints a blank line on the screen.
Line 90
prints the message that gives you the amount of numbers and their total.
Line 100
prints the average of the numbers.
Line 110
tells the computer that your progam is finished.

4.3.4 The READ-DATA Commands

There is another powerful way to tell the computer what numbers or characters to use in your program. You can use the READ statement in your program to tell the computer to get a number or character(s) from the DATA statement. For example, if you want the computer to find the average of five numbers, you can use the READ and DATA statements this way:

10 T=0
20 FOR J=1 TO 5
30 READ X
40 T=T+X
50 NEXT
60 A=T/5
70 ? "AVERAGE =";A
80 END
90 DATA 5,12,1,34,18

When you RUN the program, the computer will print AVERAGE = 14. The program uses the variable T to keep a running total, and calculates the average in the same way as the INPUT average program. The READ-DATA average program, however, finds the numbers to average on a DATA line. Notice line 30, READ X. The READ command tells the computer there must be a DATA statement in the program. It finds the DATA line, and uses the first number as the current value for the variable X. The next time through the loop the second number in the DATA statement will be used as the value for X, and so on.

You can put any number you want in a DATA statement, but you cannot put calculations in a DATA statement. The DATA statement can be anywhere you want in the program - even after the END statement, or as the first program line. This is because the computer never really executes the DATA statement; it will just refer to it. Be sure to separate your data items with commas, but be sure not to put a comma between the word DATA and the first number in the list.

If you have more than one DATA statement in your program, the computer will start READing from the first DATA statement in the program listing when the program is RUN. The computer uses a pointer to remind itself which piece of data it read last. After the computer reads the first number in the DATA statement, the pointer moves to the next number. When the computer comes to the READ statement again, it assigns the value the pointer indicates to the variable in the READ statement.

You can use as many READ and DATA statement as you need in a program, but make sure there is enough data in the DATA statements for the computer to READ. Remove one of the numbers from the DATA statement in the last program and RUN it again. The computer responds with ?OUT OF DATA ERROR IN 30. What happened is that when the computer executed the loop for the fifth time, there was no data for it to read. That is what the error message is telling you. Putting too much into the DATA statement doesn't create a problem in this program, because the computer never realizes the extra data exists.

4.3.5 The RESTORE Command

You can use the RESTORE command in a program to reset the data pointer to the first piece of data if you need to. Replace the END statement (line 80) in the program above with:

80 RESTORE
and add:
85 GOTO 10

Now RUN the program. The program will run continuously using the same DATA statement.

NOTE: If the computer gives you an OUT OF DATA error message, it is because you forgot to replace the number that you removed previously from the DATA statement, so the data is all used before the READ statement has been executed the specific number of times.

4.3.5.1 Assigning values to string variables

You can use DATA statements to assign values to string variables. The same rules apply as for numeric data. Clear the computer's memory and type the following program:

10 FOR J=1 TO 3
20 READ A$
30 ? A$
40 NEXT
50 END
60 DATA COMMODORE,128,COMPUTER

If the READ statement calls for a string variable, you can place letters or numbers in the DATA statement. Notice however, that since the computer is READing a string, numbers will be stored as a string of characters, not as a value which can be manipulated. Numbers stored as strings can be printed, but not used in calculations. Also you cannot place letters in a DATA statement if the READ statement calls for a number variable.

4.3.6 Using Arrays

You have seen how to use READ-DATA to provide many values for a variable. But what if you want the computer to remember all the data in the DATA statement instead of replacing the value of a variable with the new data? What if you want to be able to recall the third number, or the second string of characters?

Each time you assign a new value to a variable, the computer erases the old value in the variable's box in memory and stores the new value in its place. You can tell the computer to reserve a row of boxes in memory and store every value that you assign to that variable in your program. This row of boxes is called an array.

4.3.6.1 Subscripted Variables

If the array contains all of these values assigned to the variable X in the READ-DATA example, it is called the X array. The first value assigned to X in the program is called X(1), the second value is X(2), and so on. These are called subscripted variables. The numbers in the parentheses are called subscripts. You can use the value of a variable or the result of a calculation as a subscript. The following is another version of the averaging program, this time using subscripted variables.

 5 DIM X(5)
10 T=0
20 FOR J=1 TO 5
30 READ X(J)
40 T=T+X(J)
50 NEXT
60 A=T/5
70 ? "AVERAGE =";A
80 END
90 DATA 5,12,1,34,18

Notice there are not many changes. Line 5 is the only new statement. It tells the computer to set aside five boxes in memory for the X array. Line 30 has been changed so that each time the computer executes the loop, it assigns a value from the DATA statement to the position in the X array that corresponds to the loop counter (J). Line 40 calculates the total, just as it did before, but you must use a subscipted variable to do it.

After you RUN the program, if you want to recall the third number, type:

?X(3) {return}

The computer remembers every number in the array X.

You can create string arrays to store the charachters in string variables the same way. Try updating the COMMODORE 128 COMPUTER READ-DATA program so the computer will remember the elements in the A$ array.

 5 DIM A$(3)
10 FOR J=1 TO 3
20 READ A$(J)
30 ? A$(J)
40 NEXT
50 END
60 DATA COMMODORE,128,COMPUTER

TIP: You do not need the DIM statement in your program unless the array you use has more than 10 elements, see the next paragraaf, 4.3.6.2, Dimensioning Arrays.

4.3.6.2 Dimensioning Arrays

Arrays can be used with nested loops, so the computer can handle data in a more advanced way. What if you had a large chart with 10 rows and 5 numbers in each row. Suppose you wanted to find the average of the five numbers in each row. You could create 10 arrays and have the computer calculate the average of the five numbers in each one. This is not necessary, because you can put all the numbers in a two-dimensional array. This array would have the same dimensions as the chart of numbers you want to work with - 10 rows by 5 columns. The DIM statement for this array (we will call it array X) should be:

10 DIM X(10,5)

This tells the computer to reserve space in its memory for a two dimensional array named X. The computer reserves enough space for 50 numbers. You do not have to fill an array with as many numbers as you DIMensioned it for, but the computer will still reserve enough space for all the positions in the array.

4.3.6.3 Sample Program

Now it becomes very easy to refer to any number in the chart by its column and row position. Refer to the chart below. Find the third element in the tenth row (1500). You would refer to this number as X(10,3) in your program. The following program reads the numbers from the chart into a two-dimensional array (X) and calculates the average of the numbers in each row.

NOTE FOR LYNX USERS: To see a better representation of the chart below, follow [this link].

Column
Row 1 2 3 4 5
1 1 3 5 7 9
2 2 4 6 8 10
3 5 10 15 20 25
4 10 20 30 40 50
5 20 40 60 80 100
6 30 60 90 120 150
7 40 80 120 160 180
8 50 100 150 200 250
9 100 200 300 400 500
10 500 1000 1500 2000 2500

10 DIM X(10,5), A(10)
20 FOR R=1 TO 10
30 T=0
40 FOR C=1 TO 5
50 READ X(R,C)
60 T=T+X(R,C)
70 NEXT C
80 A(R)=T/5
90 NEXT R
100 FOR R=1 TO 10
110 PRINT "ROW #";R
120 FOR C=1 TO 5
130 PRINT X(R,C)
140 NEXT C
150 PRINT "AVERAGE =";A(R)
160 FOR D=1 TO 1000:NEXT
170 NEXT R
180 DATA 1,3,5,7,9
190 DATA 2,4,6,8,10
200 DATA 5,10,15,20,25
210 DATA 10,20,30,40,50
220 DATA 20,40,60,80,100
230 DATA 30,60,90,120,150
240 DATA 40,80,120,160,200
250 DATA 50,100,150,200,250
260 DATA 100,200,300,400,500
270 DATA 500,1000,1500,2000,2500
280 END

4.4 PROGRAMMING SUBROUTINES

4.4.1 The GOSUB-RETURN Commands

Until now, the only method you have had to tell the computer to jump to another part of your program is to use the GOTO command. What if you want the computer to jump to another part of the program, execute the statements in that section, then return to the point it left off and continue executing the program?

The part of program that the computer jumps to and executes is called a subroutine. Clear your computer's memory and enter the program below.

10 A$="SUBROUTINE":B$="PROGRAM"
20 FOR J=1 TO 5
30 INPUT "ENTER A NUMBER";X
40 GOSUB 100
50 PRINT B$:PRINT
60 NEXT
70 END
100 PRINT A$:PRINT
110 Z=X^2:PRINT Z
120 RETURN

This program will square the numbers you type and print the result. The other print messages tell you when the computer is executing the subroutine or the main program. Line 40 tells the computer to jump to line 100, execute it and the statements following it until it sees a RETURN command. The RETURN statement tells the computer to go back in the program to the line immediately following the GOSUB command and continue executing. The subroutine can be anywhere in the program - including after the END statement. Also, remember that the GOSUB and RETURN commands must always be used together in a program (like FOR-NEXT and IF-THEN), otherwise the computer will give an error message.

4.4.2 The ON GOTO/GOSUB Commands

There is another way to make the computer jump to another section of your program (called branching). Using the ON statement, you can have the computer decide what part of the program to branch to, based on a calculation or keyboard input.

The ON statement is used with either the GOTO or GOSUB-RETURN commands, depending on what you need the program to do. A variable or calculation should be after to ON command. After the GOTO or GOSUB command, there should be a list of line numbers. Type in the program below to see how the ON command works.

10 ?"ENTER A NUMBER BETWEEN ONE AND FIVE"
20 INPUT X
30 ON X GOSUB 100,200,300,400,500
40 END
100 ?"YOUR NUMBER WAS ONE":RETURN
200 ?"YOUR NUMBER WAS TWO":RETURN
300 ?"YOUR NUMBER WAS THREE":RETURN
400 ?"YOUR NUMBER WAS FOUR":RETURN
500 ?"YOUR NUMBER WAS FIVE":RETURN

When the value of X is 1, the computer branches to the first line number in the list (100). When X is 2, the computer branches to the second number in the list (200), and so on.

4.5 USING MEMORY LOCATION

4.5.1 Using PEEK and POKE for RAM Access

Each area of the computer's memory has a special function. For instance, there is a very large area to store your programs and the variables associated with them. This part of memory, called RAM, is cleared when you use the NEW command. Other areas are not as large, but they have very specialized functions. For instance, there is an area of memory locations that controls the music features of the computer.

There are two BASIC keywords - PEEK and POKE - that you can use to access and manipulate the computer's memory. Use of the PEEK function and the POKE command can be a powerful programming device because the contents of the computer's memory locations determine exactly what the computer should be doing at a specific time.

4.5.1.1 Using PEEK

PEEK can be used to make the computer tell you what value is being stored in a memory location (a memory location can store any value between 0 and 255). You can PEEK the value of any memory location (RAM or ROM) in DIRECT or PROGRAM mode. Type:

P=PEEK(2594) {return}
? P {return}

The computer assigns the value in memory location 2594 to the variable P when you press {return} after the first line. Then it prints the value when you press {return} after entering the ? P command. Memory location 2594 determines whether or not keys like the SPACEBAR and CRSR repeat when you hold them down. A 128 in location 2594 tells the computer to repeat these keys when you hold them down. Hold down the SPACEBAR and watch the cursor move across the screen.

4.5.1.2 Using POKE

To change the value stored in a RAM location, use the POKE command. Type:

POKE 2594,96 {return}

The computer stores the value after the comma (i.e. 96) in the memory location before the comma (i.e. 2594). A 96 in memory location 2594 tells the computer not to repeat keys like the SPACEBAR and CRSR keys when you hold them down. Now hold down the SPACEBAR and watch the cursor. The cursor moves one position to the right, but it does not repeat. To return your computer to its normal state, type:

POKE 2594,128 {return}

You cannot alter the value of all the memory locations in the computer - the values in ROM can be read, but not changed.

NOTE: These examples assume you are in bank 0. See also the description of the BANK command in Section 17, paragraph 17.4 of chapter V, BASIC 7.0 Encyclopaedia for details on banks.

4.6 BASIC FUNCTIONS

4.6.1 What is a Function?

A function is a predefined operation of the BASIC language that generally provides you with a single value. When the function provides the value, it is said to "return" the value. For instance, the SQR (square) function is a mathematical function that returns the value of a specific number when it is raised to the second power - i.e., squared.

There are two kinds of functions:

Numeric
returns a result which is a single number.
Numeric functions range from calculating mathematical values to specifying the numeric value of a memory location.
String
returns a result which is a character.

Following are descriptions of some of the more commonly used functions. For a complete list, see Section 18 of Chapter V, BASIC 7.0 Encyclopaedia.

4.6.2 The INTEGER Function (INT)

What if you want to round off a number to the nearest integer? You'll need to use INT, the integer function. The INT function takes away everything after the decimal point. Try typing these examples:

? INT(4.25) {return}
? INT(4.75) {return}
? INT(SQR(50)) {return}

If you want to round off to the nearest whole number, then the second example should return a value of 5. In fact, you should round up any number with a decimal above 0.5. To do this, you have to add 0.5 to the number before using the INT function. In this way, numbers with decimal portions equal to or above 0.5 will be increased by 1 before rounding down by the INT function. Try this:

? INT(4.75+0.5) {return}

The computer added 0.5 to 0.75 before it executed the INT function, so that it rounded 5.25 down to 5 for the result. If you want to round off the result of a calculation, do this:

? INT((100/6)+0.5) {return}

You can substitute any calculation for the division shown in the inner parenteses.

What if you want to round off numbers to the nearest of 0.01? Instead of adding 0.5 to your number, add 0.005, then multiply by 100. Let's say you want to round 2.876 to the nearest 0.01. Using this method, you start with:

?(2.876 + 0.005)*100 {return}

Now use the INT function to get rid of everything after the decimal point (which moves two places to the right when you multiply by 100). You are left with:

?INT((2.876 + 0.005)*100) {return}
which gives you a value of 288. All that's left to do is divide by 100 to get the value of 2.88, which is the answer you want. Using this technique, you can round off calculations like the following to the nearest of 0.01:
?INT(((2.876+1.29+16.1-9.534) + 0.005)*100) {return}

4.6.3 Generating Random Numbers - The RND Function

The RND function tells the computer to generate a random number. This can be useful in simulating games of chance, and in creating interesting graphics or music programs. All random (RND) numbers are nine digits, in decimal form, between the value 0.000000001 and 0.999999999. Type:

? RND(0) {return}

Multiplying the randomly generated number by six makes the range of generated numbers increase to greater than 0 and less than six. In order to include 6 (and exclude zero) among the numbers generated, we add one to the result of RND(0)*6. This makes the range 1

10 R=(INT(RND(1)*6+1)
20 ? R
30 GOTO 10

Each number generated represents one toss of a die. To simulate a pair of dice, use two commands of this nature. Each number is generated separately, and the sum of the two numbers represents the total of the dice.

4.6.4 The ASC and CHR$ Functions

Every character that the Commodore 128 can display (including graphic characters) has a number assigned to it. This number is called a character string code (CHR$) and there are 255 of them in the Commodore 128. There are two functions associated with this concept that are very useful.

The first is the ASC function. Type:

? ASC(Q) {return}

The computer responds with 81. 81 is the character string code for the {q} key. Substitute any key for {q} in the command above to find out the Commodore ASCII code number for any character.

The second function is the CHR$ function. Type:

? CHR$(81) {return}

The computer responds with Q. In effect, the CHR$ function is the opposite of the ASC function. They both refer to the table of character string codes in the computer's memory. CHR$ values can be used to program function keys. See Section 5 for more information about the use of these functions. See Appendix E of this Guide for a listing of ASC and CHR$ codes.

4.6.5 Converting Strings and Numbers

Sometimes you may need to perform calculations on numeric characters that are stored as string variables in your program. Other times, you may want to perform string operations on numbers. There are two BASIC functions you can use to convert your variables from numeric to string type and vice versa.

4.6.5.1 The VAL Function

The VAL function returns a numeric value for a string argument. Clear the computer's memory and type in this program:

10 A$="64"
20 A=VAL(A$)
30 ? "THE VALUE OF ";A$;" IS";A
40 END
4.6.5.2 The STR$ Function

The STR$ function returns the string representation of a numeric value. Clear the computer's memory and type this program:

10 A=65
20 A$=STR$(A)
30 ? A"IS THE VALUE OF ";A$

4.6.6 The Square Root Function (SQR)

The square root function is SQR. For example, to find the square root of 50, type:

? SQR(50) {return}

You can find the square root of any positive number in this way.

4.6.7 The Absolute Value Function (ABS)

The absolute value (ABS) is very useful in dealing with negative numbers. You can use this function to get the positive value of any number, positive or negative. Try these examples:

? ABS(-10) {return}

? ABS(5)"IS EQUAL TO"ABS(-5) {return}

4.7 THE STOP AND CONT (CONTINUE) COMMANDS

You can make the computer stop a program, and resume running it when you are ready. The STOP command must be included in the program. You can put a STOP command anywhere you want to in a program. When the computer "breaks" from the program (that is, stops running the program), you can use DIRECT mode commands to find out exactly what is going on in the program.

For example, you can find the value of a loop counter or other variable. This is a powerful device when you are "debugging" or fixing your program. Clear the computer's memory and type the progam below.

10 X=INT(SQR(630))
20 Y=(.025*80)^2
30 X=INT(X*Y)
40 STOP
50 FOR J=0 TO Z STEP Y
60 ? "STOP AND CONTINUE"
70 NEXT
80 END

Now RUN this program. The computer responds with BREAK IN 40. At this point, the computer has calculated the values of X, Y and Z. If you want to be able to figure out what the rest of the program is supposed to do, tell the computer to PRINT X;Y;Z.

Often when you are debugging a large program (or a complex small one), you'll want to know the value of a variable at a certain point in the program.

Once you have all the information you need, you can type CONT (for CONTinue) and press {return} assuming you have not editing anything on the screen. The computer then CONTinues with the program, starting with the statement after the STOP command.

***************************************************************************

This section and the preceding one have been designed to familiarize you with the BASIC programming language and its capabilities. The remaining four sections of this chapter describe commands that are unique to Commodore 128 mode. Some Commodore 128 mode commands provide capabilities that are not available in C64 mode. Other Commodore 128 mode commands let you do the same things as a certain C64 command, but more easily. The syntax for all Commodore 7.0 commands is given in Chapter V, BASIC 7.0 Encyclopaedia.

[top of document]

page URL: www.bigfoot.com/~c128page/c128sg/sect-04.htm
contact: c128page@bigfoot.com