Page 4
More about While Loops
You 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:
var width = prompt("How many x's would you like?
(1-10 is good)","5");
Next, we declare a few variables:
var a_line="";
var loop = 0;
And now for the important part:
while (loop < width)
{
a_line = a_line + "x";
loop=loop+1;
}
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:
- Time 1
-
- a_line = "" (because we initialized it to be "")
- loop=0 (because we initialized it to be 0)
- width=2 (because that's what the user asked for)
- 0 is less than 2 so
- a_line = a_line + "x", so now a_line = "x"
- loop=loop+1, so now loop = 1
- Back into the loop: Time 2
-
- loop=1
- width=2
- a_line = "x"
- 1 is less than 2 so
- a_line = a_line + "x", so now a_line = "xx"
- loop=loop+1, so now loop = 2
- Back into the loop: Time 3
-
- loop=2
- width=2
- a_line = "xx"
- 2 is NOT less than 2 so
- fall out of the loop and do what follows
And what follows is:
alert(a_line);
Throw up an alert box announcing a_line.
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:
while (loop < width)
{
a_line += "x"; //this was a_line = a_line + "x";
loop++; //this was loop=loop+1;
}
The first line, a_line += "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.
next page»
|