# 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!

Small and Basically yours

- Ninja Ed & Majed Marji

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

Tags

1. Sean Liming says:

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 programming

2. 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.aspx

3. 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! =^)

4. I added links to those two blog posts (in this blog post above). Thanks, Sean!

5. Computers Today (part 1 of 6)

blogs.msdn.com/…/computers-today.aspx

….

CS SPOTLIGHT: Girls in computer programming… why it matters!!!