QB005 - All The Loops

Languages : QBasic
Tools : QBASIC.EXE
Statements : Do, Loop, While, Wend, For, Next, Until, Print, Line Input, Dim, Val, Str$
Prerequisites : Install QBasic (from Tools CD #3 \ Microsoft Tools (part 2 of 2) \ QBasic - simply copy it onto your hard disk)
Estimated time : 15 minutes - not including "For Fun".

Introduction

We introduced the concept of looping earlier, and most of you grasped it pretty easily. So we're going to throw you in the deep end now. We're going to introduce you to every kind of loop available in QBasic! That's right : tremble. OK - just kidding - about the tremble bit, that is. See, if this is new to you, it may not make sense on your first (or fifth reading) - you may especially be wondering "why on earth do they have so many ways of doing practically the same thing?" and I'd have to say you've asked a good question, but let me assure you that as your programming experience builds you quickly gain a sense for which is the most effective type of loop to use in different scenarios and who knows, you may even, like me, begin to wish there were a few more types of loop...

First, I should warn you that this lesson is meant to introduce you to the gamut of loop types. You don't need to walk away feeling like you understand them all in detail and their respective pros and cons. However, you should feel confident that, as you encounter these loops in programs and in future lessons, you can either understand them at the time, or refer back here for a quick reminder.

"While" Loops

What does the above program do? Run it if you need to, or if you reckon you've figured it out already (well done in that case), tell me, what numbers will be displayed on the screen when you run?

Let's add some line numbers so I can discuss what happens on a line-by-line basis.

Line 1 simply tells the computer, "Hey! We want you to remember something, and the something will be a number (Integer), and we're going to call that something 'SomeNumber'."

Line 2 then tells the computer "Alright, the number that we want you to remember as 'SomeNumber' for the moment is 5." Key concepts : "for the moment" - i.e. we can tell the computer at any subsequent moment to remember some different number under the same 'variable' name. (Of course, when this happens, the computer will forget the previous value.)

Line 3 tells the computer that if 'SomeNumber' has a value less than 100, we should proceed, otherwise we should jump down to the line following the Wend line. In this case, the line following the Wend line is line 7. However, SomeNumber equals 5, which is less than 100, so instead of jumping to the end of the loop, we proceed on to line 4.

Line 4 prints some stuff on the screen, including the current value of SomeNumber. The current value is 5.

Line 5 assigns a new value to SomeNumber. The new value is simply the old value multiplied by two. (Yes, for reasons I have never fathomed, the way to tell a computer to multiply two numbers is to put an asterisk ('*') between them. So when you see something like '5 * 3', think '5 x 3', or in this case, when you see 'SomeNumber * 2', think 'SomeNumber x 2'.)

Line 6 is where magic happens! "Wend" means "jump back to the While statement". So we jump back to line 3.

Line 3 again! Now in case you're still struggling with the concept of us 'looping' back to an earlier line, think of a model train track with a big long straight run and a set of switches that can send the train off onto a big loop track that simply comes back and joins the main line again.

In the above program, lines 4 and 5 are the loop, and lines 3 and 6 are the switches the control whether the 'train' does the loop or continues on down the main track.

So, we've done the loop track, come the full circle and are back at line 3. It's going to decide once again whether or not to send us off on the loop (i.e. proceed to the next line) or whether we've done enough looping (in which case it will send us off to line 7, being the first line after the Wend line). How does it decide which way it will send us? It compares SomeNumber to 100 once again. SomeNumber now equals 10 ('cause it used to equal five and then we multiplied it by two). 10 is still less than 100, so it's back through the loop again.

Line 4 again. We print a slightly different message this time, 'cause SomeNumber has a different value than it had last time.

Line 5 again. SomeNumber gets multiplied by two again and now equals 20.

Line 6 again - sends us back to line 3 again again!

So now we're back at line 3 for the third time. Can you see that we're just going to keep looping and looping and looping until line 3 decides to send us off down the main line? When will that happen? When SomeNumber finally ends up equal to or bigger than 100. Each time through the loop we're multiplying SomeNumber by two, so you can see that from here (SomeNumber equals 20), SomeNumber will become 40, then 80, and finally 160. Let's skip forward to line 5 with SomeNumber = 80.

Line 5, SomeNumber = 80. We multiply SomeNumber by two, so it becomes 160.

Line 6 - sends us back to line 3.

Line 3 - compares SomeNumber to 100. This time, unlike every previous time, SomeNumber is _not_ less than 100. The 'loop condition' is "loop while SomeNumber is less than 100", and that condition is no longer met. So where do we go? To line 7 - the first line after the Wend.

Now that's a very laboured explanation of the loop, and most of you probably just skipped through it and caught on really early, but for anyone who's having trouble understanding how loops work, I suggest you read and re-read the above and really think about the above program and try to figure out for yourself what you think it should do.

"For" Loops

"For" loops are probably the most common loop in existence. A very common programming task is to loop through a set of objects and do the same thing to each one, or to repeat a certain action a certain number of times. "For" loops offer a very convenient way to do this.

Here's an example :

In the above example, we want to repeat a certain instruction a set number of times. "For" loops are ideal for this kind of task.

Note that you can 'nest' loops. 'Nesting', in programmer-speak, simply means having one inside another. So for example :


This is an example of a "nested For loop", i.e. one "For" loop inside another.  Note the use of a semi-colon at the end of the first "Print" line to prevent a line break between the word "and" and the word "InnerCounter".  If that doesn't make sense to you, remove the semi-colon and run the program again and see the difference.

Can you guess what this will do? Run it and see for yourself. Can you see that we effectively counted to 25, because we counted from 1 to 5, five times?

Small type : In fact, this is a good way to slow a computer down. They count so fast that if you just get it to count to say, a million, it will still finish very quickly, but if you get it to count to a million, and every step along the way, have it count separately another million, it effectively has to count to a trillion, which will take a veeery looong tiiime.....

Here's the bigger question : Can you see in the above example what order the counting will be done in? Let's ask it this way : which will be the first variable to reach the value 5? InnerCounter or OuterCounter? The answer is not as hard as it may seem. (Hint : if you're having trouble, run the program, and look at the output. The output will tell you exactly which variables have which values at what times.)

A "For" loop is really not much different from a "While" loop - it's just a little more concise. Here are two programs which achieve exactly the same thing, but the first uses a "For" loop and the second a "While" loop.

Can you see how the two programs achieve the same thing? Can you see that the "For" loop is much more concise?

Here's a question for you : what value does the counter variable have after the loop is finished? Why does it have that value? In other words, can you tell me in the following program what number would be printed to the screen...

Think about it - will the number 7 be printed? Or the number 0? Or the number 8? In any case, why or why not? (Hint : Look back at the example before where there is a "While" loop which does a very similar thing. Pretend you're on the final iteration of the loop, Counter equals 7, and you've just arrived at the "Counter = Counter + 1" line. Then in your brain try to walk through the program from that point on until conclusion.)

But wait, there's more! As you've probably already noticed in some of the above examples, you can count any number range - it doesn't have to start at 1 or finish at any particular number. But more than that, you can actually count backwards if you want, or by twos, or fours, or any other number you choose!

Consider the following examples :


What numbers would be displayed and why? What would the final value of Counter be?


And here?


Confused you yet? Or can you see how simple and logical it all is?

Alright, in case you're still having difficulty, first, actually type in and run the little programs, and carefully consider the output, and try to reconcile it with the program. But if that's not enough or you still have questions, perhaps comparing the above three example loops with their "While" equivalents will be helpful...


Equivalent of the first of the three preceding "For" loops.


Equivalent of the second of the three preceding "For" loops.


Equivalent of the third of the three preceding "For" loops.

We'll leave it at that for now.

"Do" Loops

Do loops are a doozy. They are the most flexible of all loop types, and by several times. Let's start off with their simplest usage...


You may have noticed that this is practically identical to an earlier example of a "While" loop.

Again, BASIC uses English-like syntax, and if you understand "While" loops, I'm sure you can figure out what the above "Do" loop does. So who cares about "Do" loops? Well, here's an example of a "Do" loop doing something a "While" loop cannot :

In the above example, we will always loop at least once. At first you're saying "but example before it would always loop once anyhow, and so they both achieve the same thing!". Well, a good observation, but consider the following two loops, which look almost identical at first glance...

Here's the question for you : Will the first loop print anything? Will the second loop print anything? Why the difference? (If you can't tell just by looking at the code, then type in the code and run it, and 'walk through' the program line by line in your mind as if you were the computer trying to run it.) (Hint : If you think they'll achieve the same thing, you'd better look again!)

In these examples, we know the numbers in advance, so it doesn't make a huge difference whether we choose the "always loop at least once" variety or just go with the more standard "loop only while the conditions are met" variety. But in real life, you'll often be dealing with comparisons that involve numbers entered by the user instead of constant numbers you as the programmer 'hard-coded' into the program. Most often you'll want the "loop only while the conditions are met" type of loop, but occasionally an "always loop at least once" type of loop is exactly what you need. Yes, a rare occurence, but I did promise I'd introduce you to all the different types of loop, so I've done it. :o)

And just in case you thought you knew it all, here's another cool feature : "Loop Until". Consider the following examples.


What is the difference between these two loops? Will they achieve the same thing? Why or why not?

Considering that BASIC is based on the English language, I don't think I need to tell you how "Until" differs from "While" - I reckon you've probably made an educated guess already, and I reckon you probably guessed right. And that's the way it is with much of programming - if you don't know, make an educated guess, and most of the time you're right. Often when I'm learning something new (and believe me, there is so much in computer programming that one could spend their whole life full time doing nothing other than learning new stuff - you never stop learning) - often when I'm learning new stuff I'll make a new program with just a few lines of code in it to test the new thing I've just learnt. Any time you're not sure how something works, it doesn't hurt to open up a new copy of QBasic and write a little program to put a theory to the test.

And of course, while you would, in real life, use this kind of loop very infrequently, you can always combine the "Until" with the always-run-at-least-once variety, making something like :

And I'm sure some of you have noticed that this achieves exactly the same as our first example of an "always-loop-at-least-once" loop, although we've used "until" instead of "while" and made a few other small changes accordingly.

For Fun

Tell me, in the following example, how many numbers will be printed and what will the last number printed be?


Trick question : how many numbers will be printed?

If your answer is anything other than "zero!", you'd better think again. If you're having trouble, try turning it into a "While" loop. (Remember that in the absence of any explicit "Step" command, the default is "Step 1".)

By the way, remember that you can come up with your own variable names. So instead of calling something "Counter", you can call it "Camelot" or "Honsolglot" or "ThisIsMyVariable" or ... let your imagination run wild!

Mega challenge : see if you can write a program that will generate a times table and display it on the screen. It will need to ask the user a few questions, and then use loops with "Print" statements inside to generate the table. Hint : "For" loops are ideally suited for this sort of task. Another hint : If you're wondering how to get input from the user and use it in a loop, read back over the "Do Loops" section, 'cause there's an example in there which does exactly that.

Copyright (C) Jonathan Field 2004
Version 20041021Thu
Comments / Suggestions