Qbasic Tutorial for beginners and children (Under Construction)


Generating random numbers

The computer does not have the capacity to choose one number randomly from a list of numbers.  This is a prerogative of the human being. However this can be simulated using three keywords.

  • The RND function
  • The RANDOMIZE statement
  • The TIMER function

The RND function

Qbasic uses the RND function to draw upon a pseudo-random sequence of numbers that are stored internally. These numbers are decimals which range from 0 to 1. So a statement like

CLS
FOR x = 1 TO 5
PRINT RND
NEXT
.7055475
.533424
.5795186
.2895625
.301948

If  you want to get random numbers between 0 and 10, proceed as follows:

CLS
FOR x = 1 TO 5
PRINT RND * 10
NEXT
7.055475
5.33424
5.795186
2.895625
3.01948

To get integers use the INT function. Remember, the INT function returns the highest number which is less that the numeric expression. 

CLS
FOR x = 1 TO 5
PRINT INT(RND * 10)
NEXT
7
5
5
2
3

 

The RANDOMIZE statement

The TIMER function

 

The only thing which continuously changes in the computer is its internal clock The TIMER function return the number of seconds elapsed since midnight.


pages viewed since January  19 2002