BASIC11.WPS
BASIC LANGUAGE PROGRAMMING
USING RANDOM NUMBERS
Random numbers may be generated for use in BASIC programs
by using the RND function. When the RND function is called,
it returns a number between 0 and .999999
We can make a random number generator in BASIC to generate
random numbers between 0 and 10, by using the following
statement: LET X = INT (RND*10) The INT function forces the computer to
output an integer. Similarly, a random number generator can be made for
numbers between 0 and 100 by using the statement: LET X = INT (RND*100)
NOTE: Random numbers are generated when the computer takes a "seed" number
from within itself. It runs this number through an algorithm which returns a value between
0 and .999999. The computer will always take the same seed and therefore
return the same series of numbers unless otherwise instructed. This is useful for
troubleshooting programs because you know what values the machine will generate!
To generate a different series of numbers we simply change the seed number.
You can specify a seed by including say a RANDOMIZE 100 or RANDOMIZE 10
instruction. The number following the word RANDOMIZE is the "seed" number.
To have truly random numbers the seed number must change each time the program
is run. To accomplish this place a RANDOMIZE TIMER statement in your program.
The timer function takes the number of elapsed seconds since midnight from the
computer's internal clock and will ALWAYS be different!
THE WORD "RANDOMIZE" MUST BE INCLUDED IN THE PROGRAM
Here is an example of a simple program which generates random numbers between
1 and 30
REM THIS PROGRAM GENERATES AND PRINTS A RANDOM NUMBER
BETWEEN REM 1 AND 30
RANDOMIZE
LET X = INT (RND*30)
PRINT X
END
(continued next page)
Assignment - Write programs to do the following:
1) Use a random number generator to generate an integer
between 1 and 20 and then have the user guess the
value of the number. The computer is to give the user
hints by telling him/her if his/her last guess was high
or low. The program should congratulate the user when
he or she finally guesses the correct number.
2) Write a program to help your younger brother with his
math. The program should use random number generators
to generate 2 numbers A and B which are between 1 and 10.
The program will then ask the user (your brother)
"What is the sum of A and B? The program will accept the
users answer (as input) and then either congratulate him
on the correct answer, or tell him to guess again.
The program will be halted when a negative number is
input!
Copyright - Barry Boyle (bboyle@kawartha.net)