Previous Page
Next Page

Using Do/While Loops

Sometimes you'll need to have a loop in your code that loops around a number of times, but there's no way of knowing how many times you'll want to loop. That's when you'll want to use a do/while loop: you want to do something, while some value is true. Script 3.9 writes out each row of numbers as always, but this time it checks first to see if a number has been used already before putting it in a cell. If it has, the script generates a new random number and repeats the process until it finds one that's unique. Figure 3.6 shows the working, finally valid Bingo card.

Script 3.9. This script prevents numbers in a given column from being used more than once.

window.onload = newCard;
var usedNums = new Array(76);

function newCard() {
     if (document.getElementById) {
        for (var i=0; i<24; i++) {
           setSquare(i);
        }
     }
     else {
        alert("Sorry, your browser doesn't support this script");
     }
}

function setSquare(thisSquare) {
     var currSquare = "square" + thisSquare;
     var colPlace = new Array(0,1,2,3,4,0,1,2,3, 4,0,1,3,4,0,1,2,3,4,0,1,2,3,4);
     var colBasis = colPlace[thisSquare] * 15;
     var newNum;

     do {
        newNum = colBasis + getNewNum() + 1;
     }
     while (usedNums[newNum]);

     usedNums[newNum] = true;
     document.getElementById(currSquare). innerHTML = newNum;
}

function getNewNum() {
     return Math.floor(Math.random() * 15);
}

Figure 3.6. Finally, we've ended up with a valid Bingo card!


To use a do/while loop:

1.
var newNum;



In the previous task, we initialized the newNum variable when we created it. Because we're going to be setting it multiple times, we're instead going to create it just the once, before we get into the loop.

2.
do {



This line starts the do block of code. One of the things you have to remember about this type of loop is that the code inside the do block will always be executed at least once.

3.
newNum = colBasis + getNewNum() + 1;



This line inside the loop sets the newNum variable to our desired number, as with previous examples.

4.
}

The closing brace signals the end of the do block.

5.
while (usedNums[newNum]);



The while check causes the do block of code to repeat until the check evaluates to false. In this case, we're checking newNum against the usedNums[] array, to see if newNum has already been used. If it has, control is passed back to the top of the do block and the whole process starts again. Eventually, we'll find a number that hasn't been used. When we do, we drop out of the loop, set the usedNums[] item to true, and write it out to the card, as in the last task.

Tip

  • A common use for a do/while loop would be to strip blanks or invalid characters off data entered by a user. But again, remember that the do block of code always gets executed, whether the while check evaluates to true or false.



Previous Page
Next Page