Over and over again


So far you have learned a number of things to do with your computer. If you think about it, though, you might wonder what good it all is. After all, you can do arithmetic with a $10 calculator without learning all this high-faluting nonsense. The computer’s ability to make decisions is interesting, but you can manage without it. You might be tempted to dismiss computer programming as a lot of high-sounding pap. In other words: “Big, fat, hairy deal!”

You would be right to dismiss computers as a waste of time if all they did was calculate and branch. But we are at last going to learn something that makes computers really useful, and it is very important that you understand the fundamental concept behind this capability.

Tools
We humans have come a long ways since the good old days of caves and woolly mammoths. One of the key factors contributing to our progress has been the development of increasingly powerful tools. We use tools for almost everything we do. We even use “tool-tools”: tools that make other tools.

Just exactly what is a tool? It is a device that allows us to execute some special function quickly and more easily than would otherwise be possible. Of course, there is a price we pay for this benefit: the cost of the tool. Suppose, for example, that I want to dig a small hole. I could grab a nearby rock and scrape out a hole in five minutes. Or I could go build myself a shovel and then dig the hole in one minute. Now, building the shovel might take me several hours, so if all I want to do is dig a single hole, I am better off using the rock. But if I expect that I will be digging quite a few holes, then the savings from the shovel can really add up. This is the central concept behind any tool. You pay a steep entry price to get the tool, but each time you use it, you enjoy a savings of time. If my shovel cost me 60 minutes to build and saves me four minutes per hole, then after fifteen holes I am ahead of the game.

Play it again, Sam
Implicit in all of this is one of the most fundamental concepts behind all technology: the concept of repetition. Doing something once is slow, cumbersome, and prone to mistakes. But if we do it over and over, we develop speed and accuracy. If we can develop a system (a tool) that allows us to reduce a huge job to a sequence of repetitive operations, we suddenly become a great deal more efficient. You want a machine to take you long distances? OK, we’ll have a piston that pushes down, turning the wheel that goes round, moving you forward. Then the piston goes back up and does it again, and again, and again. Take the ticket from the customer’s hand, tear it in half, and return the pieces to the customer. Then turn to the next person and do it again, and again, and again. Hammer the nail into the shingle; then get another nail and do it again, until the shingle is finished. Then do another shingle, and another, and another.

Again and again and again; another and another and another. This is the stuff of productivity: repetition. Repetition allows us to specialize, to learn and hone our skills. A painter can paint my house faster and better than I can, because he has painted many houses. An executive can manage a company better than I can, because he has managed many companies. Experience is nothing more than the end result of repetition. Repetition doesn’t make the wheels of civilization go round; it is the wheels of civilization going round.

The real value of the computer as a tool, then, will not lie in simple computations. The real utility of this machine is realized in repetition. If we use it over and over, we derive the true benefit of the tool. But there are two types of repetition: manual and automatic. Manual repetition is the repetition of the human; automatic repetition is the repetition of the machine. Thus, a carpenter nailing nails is engaging in manual repetition, while an automobile engine is automatically repetitive. A calculator is used in a manually repetitive manner. You, the user provide the repetition by using it over and over. The calculator itself doesn’t know or care anything about repetition. But the computer can engage in automatic repetition. The difference between a calculator and a computer is the difference between a chisel and a jackhammer, or the difference between a rifle and a machine gun, or a pen and a printing press.

The key to this automatic repetition with the computer is called the loop. Looping is the stuff and substance of computing. Any computer program without a loop is not worth writing or executing. Looping is truly the essence of computing.



The For-Loop
The easiest kind of loop to understand is called the “for” loop. If you want to get all academic, you call it an “enumerated loop”. It means “do these things that many times”. Here’s a really simple example; it does the same print statement five times.

var step;
for (
step = 0; step < 5; ++ step) {
    print (“Hip hip hooray!”);
}

This will print “Hip hip hooray!” five times. You can play with this code in the example page

Here’s how each line works:

var step;

This line declares the variable step. It means “Hey, computer, I’m going to need to use a variable, and I’ll call it step, so the next time you see step, you’ll know what I’m talking about, OK?” You might wonder why you need to go through this rigamarole. Well, how you would feel if your friend told you, “My new stromfort is really cool! I tried it out for the first time today.”? What’s a stromfort, you wonder? Your friend starts talking about something new without first explaining what it is. That’s just rude. And computers don’t take no lip from no stinkin’ users. Try it without declaring your variable first, and the computer will flip you out. 

for (step = 0; step < 5; ++step) {

There are five different ideas expressed in this one line! The first idea is the word for; it tells the computer that you are setting up a loop. The remainder of the line of code lays out the specifications for the loop according to a precise format. 

step = 0;
Next comes the initial value of step;  step is initialized to 0.  In other words,  before the computer even begins the loop, the very first thing it does is store a value of 0 into step

step < 5;
Next comes the rule for deciding when to stop the loop. Do you remember the story of the Sorcerer’s Apprentice? The apprentice, having overheard certain magic words, orders a broom to bring some water. This the broom does, but the apprentice doesn’t know how to stop the loop, and the broom continues to bring more and more water, setting the room awash. There is a lesson here for the beginning programmer: make sure you know how to terminate a loop before you start it. Being able to start a process is only half a power; knowing how to stop it is the other half. In this case, the loop will continue as long as the value of step is less than 5. As soon as the value of step is greater than or equal to 5, then the loop will stop. 

++step
OK, this one is new and strange. No it doesn’t mean “add step twice”, although that’s sorta what it looks like. Believe it or not, it means “add one to step at the end of each pass through the loop”. Back in the bad old days, when old fogey like me were writing programs, we’d have to write it out in the way that made sense: we’d write step = step + 1. That adds one to step. But after you’ve written that a few thousand times, you start getting wishing that there were a faster way to say it. We do that all the time in our regular language. Instead of saying “I am going to fix the car.” we say “Amona fix the car.” We cut corners and shorten phrases that we use all the time. That’s what computer people did here; they shortened step = step + 1 to ++step

{
The fifth idea here is the curly brace. This little bitty symbol has a big job. Remember how parentheses group together arithmetic expressions into a single bunch? Well, curly braces group together many lines of code into a single bunch. This opening curly brace tells the computer that you are beginning a bunch of commands, and all the commands between the opening curly brace { and the closing curly brace } constitute one bunch that is inside the loop. 

On to the next line of the program:

    print (“Hip hip hooray!”);

You already know what this line means. 

Now for the final line of the program:

}

This one is oh, so easy to forget — and if you DO forget it, you’re in for big trouble! This closing curly brace tells the computer “This is the end of the stuff inside the loop.” If you don’t tell it where the end is, what do you think it will do? Yeah, right: it’ll squawk “SYNTAX ERROR” and throw you out on your nose. 

Here’s another example that challenges you to make a simple improvement on a loop.

I’ll stop here. There are all sorts of lovely complications we can get into, but it’s time to take a break. Catch your breath, make sure that you’ve got a firm grip on the basic idea of the for-loop, and in the next lesson we’ll start getting really loopy.

Conclusions
The loop on the computer is closely analogous to the moveable type on the printing press. The invention of moveable type was profoundly important because it allowed each type character to be used over and over again, in different words on different places on the page. This made possible the printing press. At the same time, moveable type imposed severe constraints on the creative freedom of the author. The characters could only fit into the press in a defined fashion; no longer could the author scatter words across the page in any fashion that struck his fancy. The use of illustrations was severely curtailed, and color was impossible to print. Despite these restrictions, the printing press is ranked as one of the most important inventions of human history.

In the same way, the loop is the critical concept that makes the computer a useful, practical tool. The computer imposes constraints on our organization of data just as the early printing presses constrained the presentation of information on the printed page. The computer is another landmark in the history of civilization. But there is one big difference between the printing press and the computer: the printing press cost a lot of money and required a lot of expertise to utilize. The computer is accessible to everyone, not just a few experts. You can program this machine; you can guide it where you will. What will you print with your new press, Herr Gutenberg?