|
More about while loopsYou should have seen as many x's as you asked for. Let's go over this: First, we ask for the number of x's:
Next, declare a few variables: var aLine = ""; And now for the important part:
This says, "while the variable loop is less than the requested width of the row of x's, add another x to the line and then add one to the value of loop." This loop will keep adding an x to the line and adding one to the value of loop until loop is no longer less than the requested width. Here's a timeline of what happens when a person chooses two x's at the prompt():
And what follows is: alert(aLine); Throw up an alert box announcing aLine. This sort of loop is so common that programmers have developed a few shortcuts. Using the shortcuts, the while loop could have been written like this:
The first line, aLine += "x", says "add x to myself." This shortcut works with numbers, too. If you have a_number = 5, and you write, a_number += 3, it's just like writing a_number = a_number + 3. Programmers are lazy; they're always coming up with shortcuts like this. The next line, loop++, means "add one to myself." So, loop++ is the same as loop = loop +1, which could also be written loop += 1. Each of these is equally good. Which one you use depends on how lazy you are. Just like there's more than one way to add 1 to a number, there's more than one way to write a loop. while loops aren't the only kind of loops out there. Another popular one is the for loop. |
||||||||||||