Relearning MSX #31: Loops in MSX-C
Posted by Javi Lavandeira in How-to, MSX, Retro, Technology | October 21, 2015In the last post we finished our look at the conditionals in MSX-C. Today we’re going to learn something much more fun: loops. As you may know already, loops are structures that run the same code again and again a specific number of times, or until a certain condition occurs. Loops are an essential part of every non-trivial program, so it’s very important that we learn what types there are and how to use them.
Let’s get to it.
Loops that repeat a given number of times: the for statement
There are several ways to implement loops in C, but the for statement is probably the most commonly used. It resembles the FOR…NEXT command in MSX-BASIC.
The syntax of a for look in C is like this:
for ( setup ; condition ; update ) statement
When a for loop runs, the first thing that happens is that the code in the setup block runs once (and only once!). After that, if condition is true then the code in the statement block is executed, followed by the code in the update block. Then the loop goes back to condition and does the same thing again and again for as long as condition is true.
This flowchart illustrates the process:
The following example program shows how to use a for loop. First, it initializes the variable i to 1 (this is the setup block). Then it checks the condition (whether i is equal to or lower than 10). As long as condition is true, it prints the ‘A’ character on the screen (this is the statement block), and finally it adds 1 to the i variable (the update block) before jumping to check the condition again:
In other words:
- setup: Set variable i to 1
- condition: Check whether i <= 10. If true, continue to 3. If false, jump to 6.
- statement: Print character ‘A’ on the screen
- update: Add 1 to variable i
- Jump to 2
- Loop completed
In this case the loop structure is almost identical to a FOR…NEXT loop in BASIC:
FOR I=initial_value TO final_value STEP increment statement(s) NEXT
Loops with this structure are very easy to implement in C:
for (i = initial_value; i <= final_value; i = i + increment) statement for (i = initial_value; i >= final_value; i = i - decrement) statement
However, for loops in C are more powerful than this. They’re not limited to incrementing a variable by a given value. For example, we could obtain powers of two by multiplying instead of adding:
The following is a more useful example. The loop keeps reading the keyboard and asking the user a question while the answer is different from ‘y’:
As you can see, the for loop is not imited to incrementing or decrementing a variable. Remember that the most important part is to have a suitable condition, and something that makes the value of the condition change. This last part can be the update block, or something in the statement block.
Using empty for loops to generate delays
In BASIC it is common to use the FOR loop to generate a delay, like this:
FOR I=1 TO 1000:NEXT
This is an example of an empty loop. The loop doesn’t do anything other than count until the I variable reaches the final value. We can implement the same thing in C very easily:
for (i = 1; i <= 1000; i = i + 1) ;
Notice the semicolon (“;”) following the for. The semicolon is there to tell the compiler that that’s where the loop body ends. This achieves the same result as the previous FOR…NEXT loop: it increments the variable i until it contains 1000. As an example, look at the program below. It prints the ‘A’ character on the screen 400 times, counting from 1 to 6000 after each one:
Shorthand style for arithmetic assignments
If you’ve typed this post’s programs in your computer you may have noticed that typing “i = i + 1” or “i = i * 2” starts getting annoying pretty soon. No doubt Brian Kernighan and Dennis Ritchie felt the same, so they added an abbreviated notation for these arithmetic assignments:
For example, if we want to increment variable x by 5, we can just type x += 5. Similarly, to multiply variable x by 3 and assign the result back to itself we can write just x *= 3.
Additionally, very often we find ourselves incrementing or decrementing variables by 1. C has special operators for this too: ++ for incrementing a value and — to decrement it:
Let’s see a program that uses these:
The program above has two loops. The first one counts from 1 to 10 in increments of one. The second loop keeps multiplying the variable i by 3 while the result is lower than or equal to 2187:
The good thing is that these abbreviated operators aren’t for exclusive use of the for loops. We can use them anywhere in our programs. Now that we know about them you won’t see me write i = i + 1 again. I’ll be using the shorthand forms all the time.
Loops that repeat for as long as the condition is true: while and do
We’ve seen that we can use the for statement to write any kind of loop. However, there are times when we don’t care about having setup and update blocks and just need to repeat a block of code as long a a condition is true.
For these situations we have the while and do statements.
Let’s see while loops first. The generic form for these loops is like this:
while (condition) statement
This just means that the code in the statement block will run again and again as long as condition is true. The following flowchart illustrates this:
The following program shows a typical usage of the while loop. It keeps printing on the screen any character entered on the keyboard, until the character is ‘q’:
If you try this program you’ll see that it keeps repeating whatever you type on the keyboard, until you press the ‘q’ key. At that moment the program ends.
The main characteristic of while loops is that the statement block may or may not run even once. If the condition is false from the start then statement will not run at all. However, there are some situations where we need to run the statement block at least once and then check condition at the end. That’s what the do loop is for. The general form is like this:
do statement while (condition)
The first thing that happens in this case is that statement runs once. Then the program keeps repeating statement while condition is true. This is the flowchart:
It is very common to enclose the statement block in braces whenever we’re using a do loop, even when statement contains a single line, in order to make it easier to see in the code where the condition is, like this:
do { statement } while (condition);
This program shows a do loop in action:
First, the program prints a message on the screen and asks for a character from the keyboard. The program repeats these same steps until you enter a character between ‘1’ and ‘5’.
Summary
We’ve learnt how to create loops in C. We’ve seen how to use the for loop in several ways, including a way to create delays. We’ve also learnt about while and do…while loops. In addition to that we’ve seen the shorthand notation for arithmetic assignment and variable increment/decrement.
In the next post…
Sometimes loops aren’t enough and we need a couple of extra ways to control the flow of our programs: break out of loops, go to especific locations in the program (yes, the dreaded goto statement!), choose a result from a selection of a few different values, etc. We’ll see these in the next post.
This series of articles is supported by your donations. If you’re willing and able to donate, please visit the link below to register a small pledge. Every little amount helps.
Javi Lavandeira’s Patreon page