Freigeben über


Small Basic: Three Loop Counters

First, let’s look at a method to create a While loop that removes root beer bottles from the wall:

bottles = 99

While (bottles > 0)

    TextWindow.WriteLine(bottles + " bottles of root beer on the wall!")

    bottles = bottles - 1

EndWhile

This code works well, but it’s not the best way to do the job. Since the goal is to repeat the “X bottles of root beer on the wall” 99 times, it’s better handled by a For loop:

For bottles = 99 To 1 Step -1

  TextWindow.WriteLine(bottles + " bottles of root beer on the wall!")

EndFor

We can also use Goto to do the same thing, but this definitely isn’t the best way!

bottles = 99

Again:

TextWindow.WriteLine(bottles + " bottles of root beer on the wall!")

bottles = bottles - 1

If (bottles > 0) Then

  Goto Again

EndIf

Can you see why the For loop is the best way? Not only is it the fewest lines (only three), but it also uses the simplest logic. It continues the one WriteLine statement 99 times, and the first line of the For statement makes it very clear that’s what it’s doing.

   

Do you have any questions? Ask us! We're full of answers and other fine things!

Head to the Small Basic forum to get the most answers to your questions: 

https://social.msdn.microsoft.com/Forums/en-US/smallbasic/threads/   

And go to https://blogs.msdn.com/SmallBasic to download Small Basic and learn all about it!

  

Small and Basically yours

- Ninja Ed & Majed Marji

 

================

See Also:

Comments