Young Coder
Young Coder

Reputation: 21

How do I fix the error "subscript out of range" in QBASIC?

I'm trying to create a code that generates random numbers within the range 10-30 but making sure that no number is repeated. It shows "subscript out of range" on NumArray(Count) = Count when I run the code.

'Make an array of completely sorted numbers
FOR Count = 10 TO 30
    NumArray(Count) = Count  
NEXT Count  
RANDOMIZE TIMER  
FOR Count = 10 TO 30
    Number = (RND * (31 - Count)) + 10
    PRINT #1, NumArray(Number)
    FOR Counter = Number TO 30 - Count
        NumArray(Counter) = NumArray(Counter + 1)
    NEXT Counter 
NEXT Count

This isn't actually my code. Copied and pasted for my assignment.

Upvotes: 0

Views: 1384

Answers (2)

MemReflect
MemReflect

Reputation: 551

It looks like you're missing some DIM statements.

Variables containing numbers have type SINGLE by default, so you might see something like FOR Counter = 18.726493 TO 20 because the RND function returns a number between 0 and 1, excluding 1, meaning you will be trying to use NumArray(18.726493) which will not work.

Arrays that are not explicitly declared can only have 11 items with an index from 0 to 10, but the range 10-30 requires you to store 21 items (30 - 10 + 1 = 21). You can also specify a custom upper and lower bound if it will make your code easier for you to understand. Add these lines before the first line in your code shown above:

DIM Number AS INTEGER
DIM NumArray(10 TO 30) AS INTEGER

This will ensure Number only contains integers (any fractional values are rounded to the nearest integer), and NumArray will work from NumArray(10) to NumArray(30), but you can't use NumArray(9), NumArray(8), NumArray(31), etc. The index must be in the range 10-30.

I think that should fix your code, but I don't know for certain since I don't fully understand how it is supposed to work. At the very least, it will fix the type and subscript problems in your code.

Upvotes: 5

Azathoth
Azathoth

Reputation: 115

You need to declare the array:

'Make an array of completely sorted numbers
DIM NumArray(30) AS INTEGER
FOR Count = 10 TO 30
    NumArray(Count) = Count  
NEXT Count  
RANDOMIZE TIMER  
FOR Count = 10 TO 30
    Number = (RND * (31 - Count)) + 10
    PRINT #1, NumArray(Number)
    FOR Counter = Number TO 30 - Count
        NumArray(Counter) = NumArray(Counter + 1)
    NEXT Counter 
NEXT Count

Upvotes: 0

Related Questions