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
Anonymous
August 18, 2015
I still think goto statements lead to bad programming. Use them when learning GW Basic many years ago, but it doesn't transition to structured programmingAnonymous
August 18, 2015
I think that's very fair. Majed and I wrote this article to really explain what you're describing: blogs.msdn.com/.../small-basic-spaghetti-code.aspxAnonymous
August 18, 2015
Also, here's Vijaye's reasoning for including GoTo in Small Basic: blogs.msdn.com/.../small-basic-and-the-goto-keyword.aspx He wrote that 7 years ago! =^)Anonymous
August 18, 2015
I added links to those two blog posts (in this blog post above). Thanks, Sean!Anonymous
January 30, 2016
Computers Today (part 1 of 6) blogs.msdn.com/.../computers-today.aspx .... CS SPOTLIGHT: Girls in computer programming... why it matters!!! blogs.msdn.com/.../cs-spotlight-girls-in-computer-programming-why-it-matters.aspx