Files
RCBASIC4/doc/files/loops.txt
2024-10-24 22:51:34 -04:00

62 lines
2.1 KiB
Plaintext

#title RCBasic Loops [RCBasic Doc]
#header LOOPS
RC BASIC has 3 types of loops: <b>FOR</b>, <b>WHILE</b>, and <b>DO</b>.
The <b>FOR</b> loop repeats a block of code and increments a counter each time it finishes the block between <b>FOR</b> and <b>NEXT</b>. When the counter reaches a certain value the <b>FOR</b> loop stops.
#code
For I = 1 To 5
Print I
Next
#/code
The above code will output the numbers 1 to 5 to the console. Optionally you could use the <b>STEP</b> keyword to set the number that the counter will increase by. Look at the following:
#code
For I = 1 To 5 Step 2
Print I
Next
#/code
The above code will output the numbers 1, 3, and 5 to the console. The <b>STEP</b> keyword increases I by 2 each time through the <b>FOR</b> loop.
<b>WHILE</b> loops will execute a block of code while a certain condition is true.
#code
I = 0
While I < 5
Print I
I = I + 1
Wend
#/code
The above code will output the numbers 0 to 4. It will not output the number 5 because if ( I < 5 ) is false the loop will not repeat.
The <b>DO</b> loop is similar to the <b>WHILE</b> loop with an exception. The <b>WHILE</b> loop checks for the loop condition at the start of the loop but the <b>DO</b> loop checks for the loop condition at the end of the loop. What this means is that a <b>WHILE</b> loop will never execute if the condition is false at the start but the <b>DO</b> loop is guaranteed to execute at least once before it checks if the condition was true or not.
The <b>DO</b> loop is also unique in that it has 3 different forms. Here is the simplest form of the <b>DO</b> loop.
#code
Do
Print "HELLO WORLD"
Loop
#/code
The code above will continue to output HELLO WORLD to the console infinitely.
#code
I = 0
Do
Print I
I = I + 1
Loop While I < 5
#/code
The above code will output the numbers 0 to 4 to the console. This form of the <b>DO</b> loop will continue to loop while the loop condition is true.
#code
I = 0
Do
Print I
I = I + 1
Loop Until I = 5
#/code
The above code will output the numbers 0 to 4 to the console. This form of the <b>DO</b> loop will continue to loop until the loop condition is true.