For/Next/Step

If you have questions about any aspect of QBasic programming, or would like to help fellow programmers solve their problems, check out this board!

Moderators: Pete, Mods

Post Reply
jejump
Coder
Posts: 11
Joined: Wed Jun 25, 2014 7:54 am

For/Next/Step

Post by jejump » Sat Apr 18, 2020 7:21 am

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

MikeHawk
Coder
Posts: 31
Joined: Sun Jul 08, 2018 11:23 am

Re: For/Next/Step

Post by MikeHawk » Sat Apr 18, 2020 10:49 pm

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:

Code: Select all

FOR a = b TO c STEP d
  PRINT a
NEXT a
QBASIC is actually doing:

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
Modifying the loop control variable works but it's also something you should avoid doing (it's a bit dirty.) However, you could do:

Code: Select all

FOR a% = 0 to 7
  PRINT 2 ^ a%
NEXT a%
Alternatively, you may try using DO...LOOP

Code: Select all

DIM a AS INTEGER

a = 1
DO
  PRINT a
  a = a * 2
LOOP UNTIL a = 256
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.

jejump
Coder
Posts: 11
Joined: Wed Jun 25, 2014 7:54 am

Re: For/Next/Step

Post by jejump » Sun Apr 19, 2020 12:35 pm

You're absolutely right!! I had a case of mathematical dyslexia. :roll:

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

Post Reply