Can some nice programmer enlighten me on the usage of STEP in a FOR - NEXT loop? I've been trying the following code running on the MS-DOS 6.22 distribution of QBASIC (whatever version that is????).
For A = 1 TO 128 STEP A^2
PRINT A
NEXT
To try to achieve the screen output of:
1
2
4
8
16
~~~
128
Instead I get this:
1
1
1
1
1
~~~~ etc,
I ended up doing this:
For A = 1 TO 128
PRINT A
A = A * 2 -1 ' Definitely need the -1. NEXT instruction increments +1
NEXT
Ditching the use of STEP altogether. This works, but I just wonder why the other way doesn't? I am reasonably sure that I made the former way work years ago, but I was probably using QBX 7 then. Maybe I am forgetting something about the way it should be formatted. I've tried round brackets (A^2) and nothing changed. Anyway, it's working with method 2.
Thanks for the love <3
Jj
For/Next/Step
Re: For/Next/Step
Hi there. To keep things short, the FOR...NEXT loop is initialized once by QBASIC before it starts, so you can't mess with the upper limit ("128" in your example) and you can't modify the value fed to STEP either.
When you type:
QBASIC is actually doing:
Modifying the loop control variable works but it's also something you should avoid doing (it's a bit dirty.) However, you could do:
Alternatively, you may try using DO...LOOP
EDIT: I didn't look at what you were doing, only what you expected. Just as a side note, A ^ 2 will return the square of A, while you were looking for powers of two, which would be 2 ^ A. Had your initial attempt worked, returned values would be 1 ^ 2 (1,) 2 ^ 2 (4,) 3 ^ 2 (9,) 4 ^ 2 (16,) not 1, 2, 4, 8, etc.
When you type:
Code: Select all
FOR a = b TO c STEP d
PRINT a
NEXT a
Code: Select all
from = b
to = c
step = d
a = from
GOTO Next:
For:
PRINT a
a = a + step
Next:
IF a <= to THEN GOTO For
Code: Select all
FOR a% = 0 to 7
PRINT 2 ^ a%
NEXT a%
Code: Select all
DIM a AS INTEGER
a = 1
DO
PRINT a
a = a * 2
LOOP UNTIL a = 256
Re: For/Next/Step
You're absolutely right!! I had a case of mathematical dyslexia.
Anyway, it's a disposable program. I only need it to show me bits changing in a memory resident program I created in MASM. It did the job.
Thanks for the reply!
Jj
Anyway, it's a disposable program. I only need it to show me bits changing in a memory resident program I created in MASM. It did the job.
Thanks for the reply!
Jj