ArcBasicDocs
Chapter 4

Doing things again and again

Computers never get bored. A loop repeats some instructions as many times as you like: ten times, a million times, or until the player wins.

Three kinds of loop

04_loops.absOpen in editor
; Repeating things with For, While and Repeat; For counts for youFor n = 1 To 5	Print "5 x " + n + " = " + 5 * nNext; Step changes how it countsWrite "Countdown:"For n = 5 To 1 Step -1	Write " " + nNextPrint " lift off!"; While keeps going as long as something is truetotal = 0count = 0While total < 20	count = count + 1	total = total + countWendPrint "1 + 2 + ... + " + count + " = " + total + " (past 20!)"WaitKeyEnd
A times table, a countdown and a running total
  • For n = 1 To 5 … Next runs the lines in between once for each value of n: first 1, then 2, and so on up to 5. Use it when you know how many times to go round.
  • Step changes how n counts. Step -1 counts down, and Step 2 would count 1, 3, 5…
  • While … Wend keeps going as long as something is true. It checks first, so it might not run at all.
  • Repeat … Until keeps going until something is true. It checks at the end, so it always runs at least once.

Write is like Print, but it doesn't start a new line afterwards. That's how the countdown stays on one line.

The full guessing game

With a loop, the guessing game can keep going until you get it, and count how many tries you took:

04_guess.absOpen in editor
; Guess my number - keep going until you get itSeedRnd MilliSecs()secret = Rand(1, 100)tries = 0Print "I'm thinking of a number from 1 to 100."Repeat	guess = Input("Your guess? ")	tries = tries + 1	If guess < secret Then Print "Higher!"	If guess > secret Then Print "Lower!"Until guess = secretPrint "Yes! It was " + secret + ". You took " + tries + " tries."If tries <= 7 Then Print "That's excellent guessing."WaitKeyEnd
The guessing game: higher, lower, and a win in 5 tries

Clever trick: always guess halfway between the numbers it could still be. You'll never need more than 7 guesses for 1 to 100.

Getting out early, and loops that never end

Exit leaves a loop straight away. Repeat … Forever loops for ever, unless something inside uses Exit.

If a loop's condition never comes true, your program goes round for ever and seems to freeze. That's a very common bug. If it happens, just close the program's window and look for the mistake.

Try this

  • Ask which times table to print, and print it from 1 to 12.
  • Print all the even numbers from 2 to 50 using Step.
  • Give the guessing game a limit of 10 tries, and say "Out of guesses!" when they run out. (Hint: Until guess = secret Or tries = 10.)