# 8 Looping |
# 8 Review Questions | # 8 Assignment |
One thing that computers are very very very very good at is repetitive tasks. Anytime we have steps that repeat the same or similar actions over and over, then a computer would be the right tool for the job. We have three ways of controlling repetition or 'iteration' as some programmers call it. Each way has its applications, the times when it is the best tool to get a program working correctly. Here are the concepts you need, then read below to see how to code these loops.
In the old days, programmers could make due with only one type of loop, but the programs were convoluted and hard to work with. Now that we have these three tools, always try to pick the best tool for the job you are doing. Imagine a carpenter trying to drive a nail with a screwdriver! He might get the job done, but it won't be the most efficient way.
Looping Construct | When to Use | Example Situations |
for ...loops |
When you, the programmer, already know the number of times you want something repeated. Also, if the computer can easily calculate how many times to repeat. The for loop is sometimes similar to the while...do... loop because it repeats as long as the condition is true and checks at the top of the loop. |
Calculate loan payments for 24 months. Create a design that repeats 4 times. Counting by 1's, or 5's, or even negative values. |
do...while... loops also known as a post-test loop since it checks the condition at the end. |
This construct says to do some steps while a certain condition is true. The steps can be simple or complex, but it performs the statements, then checks the condition at the end of the loop. So it always executes at least once. |
When the user clicks a button to play a game, we assume they want to play at least once, or why would they click the button? Ask the user to enter some required data. If they so not fill it in, the program repeats until the user fills in the data. |
while...do... loops also known as a pre-test loop since it checks at the top of theloop |
When the loop condition should be checked first, before performing the statements within the loop. This loop may not execute at all if the condition is false at the start. One of the most common uses is to first have the user input some data, then do a check to see if the data is valid, and if not, enter the loop where the user sees an error message and is asked again to enter correct data. This is called a priming input with a pre-test loop. |
In a high school, ask the user to enter their grade level. If the grade is not 9-10-11 or 12, tnen repeat the message "Must be grade 9-12, please re-enter correct grade" and ask the user to input the grade, over and over until they get it right. The important part of this is that the program doesn't move ahead with "bad" info. The data is checked and is found to be acceptable before the program moves on. |
Let's start with an example:
for (var count = 0; count < 5; count ++) { document.writeln( count ); }
This is a very simple loop but let's look at the way it works. In the first line, after the keyword 'for' and inside the parentheses, we have three parts separated by semicolons.
The first part is the initialization expression. We create a variable named count and give it a starting value of 0. Since this variable is created inside the loop, it is only able to be used within the loop. But that's ok because that what we created it for. If we want it to be useful outside of the loop we have to create it outside of the loop.
The second part is the condition, count < 5. As long as that is true, then the statements of the loop will execute.
The third part is the update statement. It gives us a lot of flexibility because it can be most anything we need to have done. In this case, count++ just adds one to the value of count, in other words, it counts by ones.
Next we have some statements inside of {...} curly braces. Our example just has one, but there can be as many as we want. These lines are called the body of the loop. This example will just display the numbers from 0 to 4 and then stop. What makes it stop? As soon as the value of count is equal the 5, then count is no longer less than 5 and the loop terminates.
Click here to run the little program above
Here is a for loop that counts by 2's.
function countByTwos() { for( var count = 0; count < 100; count+=2) { document.write( count ); } } // end function
Always make sure your loop has a way to terminate before running the program. Here is an example of an infinite loop (very bad);
function infiniteLoop() { for ( var dummy = 0; dummy < 10; dummy-- ) { // uh oh, dummy will always be less than 10, so loop will never terminate! document.writeln( dummy ); } } // NEVER DO THIS!
Do ...while... loops will repeat until the condition is no longer true, but since the condition gets checked at the bottom of the loop, the loop always will execute the first time, then check to see if it should repeat. Here is a sample that will just count by 5's up to 100.
function demoDoWhileLoop() { var count = 0; // need to create a variable and initialize it to zero before start of loop do { // start the body of the loop here document.writeln( count ); count+=5; // bump up the loop control variable by 5 }while ( count <= 100 ); // condition is checked at the bottom of the loop document.write ("Done"); } // end function
A few critical things to explain here. First of all the general format of a do... while... loop is
do { statement(s); } while ( condition );
The first time through,
the statements in the body of the loop will always execute. So our sample
will print the 0 and then add 5 to the variable count. As long as the condition
is true, the loop will continue to execute, so since 5 is less than 100
it repeats. Note that the condition says 'less than or equal to 100'. That
is because we want the program to print the value 100 before it terminates.
So the value of count will be 105 when the loop exits. It is the programmer's
responsibility to initialize the loop control variable, and to update the
loop conrol variable so that sooner or later the condition tests false,
or the loop will be infinitely repeating. Note that in the for loop, those
things were built in to the for loop. Click here to see a demo of this function.
This type of loop may actually not execute at all. One of it's major uses is to double check some data that was entered by a user before proceding to process some data. So a simple example would be to ask the user to enter an ending value, then count until we get to that value. But what if the user enters a 0, or worse yet some negative number. That would create an infinite loop and leave you, the programmer, looking like a dimwit. So the logic is this: We get the data from the user, then, at the top of the loop, we check for 'bad' data. If it is bad data, we enter into the body of the loop where the user sees a descriptive comment and another chance to enter the data correctly. But had they done it correctly the first time, the loop gets skipped entirely and no one even knows it was there.
A handy method for getting the data is the prompt() method. The prompt() method uses two parameters, the message that tells the user what to enter, and a default value. For example:
var someData = prompt("Enter your name here:"' " ");
Here I used an empty string for the default value. Prompt() always returns the data as a string value, so we use the parseInt() or the parseFloat() method to change the string data to a number format.
In this loop structure, we first get an initial input from the user. That's the prime to determine if the loop needs to execute. The top of the loop does a test on the priming input, and if needed, the body of the loop will execute. The user cannot get past this point in the program without giving some acceptable input. So you see why this is called a pre-test loop with a priming input.
function getValidData() { var endvalue; // program will count up to this number endvalue=prompt("Enter the end value:", " ");//This is the priming input. If good number, then loop is skipped endvalue = parseInt(endvalue); while ( endvalue >=0 ) { // check here for bogus values endvalue= prompt ("End Value must be greater than zero." , " "); } // program cannot get past here with a 'bad' value for ( var i = 0; i < endvalue; i++ ) //proceed on with a good value document.writeln( i ); // since only one line in the loop body, no { } are needed document.write("Thank you for giving me a valid number."); } // end function
Click here to see this one work, and be sure to type in a bad value such as -5, or 0 to see how it catches you.
Just a couple more example programs. One of the most common types of programming errors is having a loop that repeats once too many times, or once too few. Both of those are bad, since they produce output that looks pretty good unless you study it closely. These are called "Off by One Bugs" or OBOBs for short.
For example, a simple game. The computer will make up a number between 1 and 100, and all you have to do is guess it. The computer will prompt you, and it will also count your guesses. Too many wrong guesses and you will get some flack from the machine!
There is a bug in this program however, even though the game works (sort of). Click here to view the code, and see if you can find the problem. There are some hints.
Did you find the OBOB? Check the count variable. Note that it starts as 0, but forgets to count the first guess. So the count is always off by one. That is the OBOB, but also notice the use of loops and if statements to make the prompts react to the user's guess each time. Think about some other games you know. After lesson 9 on Arrays you may be able to program some card games or dice games in JavaScript.
Another example - nesting one loop inside of another. Actually any of the logical constructs such as branching or looping can be nested in any way you want to get the job done. Here we want to create a simple triangular design such as this:
X XX XXX XXXX XXXXX |
For this we need to create one for loop to repeat 5 times. It controls the number of rows and basically all it does is print a carriage return, and its loop control variable 'i' provides a counter for another loop to print the correct number of x's in each row before moving on. The inner loop will execute once the first time through, then the outer loop changes i to 2 and so the inner loop executes twice the second time through. This pattern keeps up so we get three x's, then four, then five in the last row. The code looks like this:
function makeTriangle() { for ( var i = 0; i < 5 ; i++ ) {// start of outer loop to control number of rows for (var j = 0; j < i ; j ++ ) {//inner loop to print x's document.write("x"); } // end of inner loop document.writeln(" "); // just prints a linefeed (carriage return) } // end of outer loop } // end of the function |
Click here to demonstrate the triangle program