Loops![[next]](../../img/ltp/arrow-next.gif)
Computers are good at doing the same thing over and over, perhaps with slight changes each time. This lesson will teach you "loops", the programmer's way to do things repeatedly.
When making an hour-by-hour schedule for your day, you realized you only ever do one thing!
|
1
2 3 4 5 6 print(html("<h1>My daily schedule</h1>")) var x = 1 while (x <= 11) { printp(x, "pm: Learn to program.") x = x + 1 } |
Click to run the code. |
As you can see, loops can save a lot of typing.
This kind of loop is called a while loop. The code between the curly braces { ... }, called the "body", is run repeatedly, while (as long as) the "condition" (x <= 11) is true. In other words, the condition is checked, and if it's true, the body is run, and then the condition is checked again, and so on. If the condition is ever found to be false, the loop is over.
In this particular loop, we are doing some counting in order to run the loop exactly 11 times. The variable x is initialized to the value 1 before the loop. The loop's check succeeds the first time, because 1 <= 11, and the body is run. The body increments x to 2, and so on. As soon as x becomes 12, the check fails, the body isn't run, and the loop ends.
The diagram below shows the parts of a typical loop.
Exercise: More hours. Do you ever wish there were more hours in the day? What if you could stay up programming until "a thousand o'clock" (1000pm)? Change the program to reflect this.
Exercise: Pushing the envelope. Now that you've discovered the power of loops, how far can it be stretched? AppJet has a limit on how much stuff you can print, though it's quite high. Try having the loop run a million times. What's the largest count you can reach before getting a "too much stuff" error?
Exercise: No increment. Try removing the increment line x = x + 1. What happens? This is a very common mistake for any programmer to make!
while loop.Not all loops have an increment, and there are ways to end a loop other than its condition becoming false. We'll learn about those in subsequent chapters. But the initializer-condition-increment loop, as in the example above, is so common that most languages (JavaScript included) have a special syntax for it.
|
1
2 3 4 5 print(html("<h1>My daily schedule</h1>")) for (var x = 1; x <= 11; x = x + 1) { printp(x, "pm: Learn to program.") } |
Click to run the code. |
This is called a "for loop". The initializer, condition, and increment are put into the loop statement itself, so you can focus on what the loop actually does. See the diagram below.
Exercise: Square Numbers. Can you write a program that prints the first 10 square numbers?
for loop.