Available on: all targets
See also: DO...LOOP WHILE...WEND REPEAT...UNTIL

FOR...NEXT

The FOR...NEXT is a basic tool for executing a block of code a specified number of times. It is a control structure that creates a loop, which is a segment of code that is repeated until a certain condition is met. Once inside the loop, the index used to loop can be read and modified by the program as if it is a normal variable.

Normally, the index counter is increased by 1 unit at every turn of a FOR...NEXT loop. When the current value exceeds that of the last number specified, the loop is terminated. STEP is used to change the size of increase in the index value.

It should be noted, however, that none of the terms of the loop must be considered constant. The loop, in fact, continues as long as the condition for which the index is included within the indicated limits is true. If these limits are expressed by variables or, more generally, expressions, these values ​​are recalculated at each turn, to ensure compliance with the limits. The variable index itself can be updated within the loop, and therefore it is possible to interrupt a cycle or continue it definitively, by operating on this variable. Finally, one can jump in and out of the loop, without problems.

The FOR...NEXT loop is ideal for performing the same operation a specific number of times. It can be used to create tables of values, such as a multiplication table. It is often used in algorithms that require repeated calculations, such as calculating the factorial of a number. Generally speaking, you can use the FOR...NEXT when you know the number of iterations in advance, want to perform a sequence of operations repetitively and you need a simple and effective control structure.

SYNTAX

 FOR var = start TO end [ STEP increment ]
    ...
 NEXT [var]


Legend
  • id : identifier
  • type : datatype
  • v : value
  • "..." : string
  • [...] : optional

EXAMPLE

 i = 0
 FOR i = 1 TO 100 STEP 2
    PRINT i
 NEXT


Used in:

ABBREVIATION: FoNx

Join BASIC 10Liner Contest with ugBASIC!

An interesting competition is held at the beginning of each year: the BASIC 10Liner Contest. It is possible to use ugBASIC to participate in the next "BASIC10Liner" competition, in the following categories:

  • PUR-120 - A game in 10 lines of max 120 characters (w/abbrev.)
  • EXTREME-256 - A game in 10 lines of max 256 characters (w/abbrev.)
  • SCHAU - Any program in 10 lines of max 256 characters (w/abbrev.)
In order to reduce space you can use this abbreviation for this instruction:

FOR...NEXT ↔ FoNx

Any problem?

If you have found a problem with this keyword, if you think there is a bug or, more simply, you would like it to be improved, open an issue for this example on GitHub.
Thank you!

open an issue BACK TO KEYWORDS