While loop

While loop

In a previous example a for loop was used to generate a multiplication table. This kind of loop was used because the number of repetitions (or iterations) was known in advance. In the next example the program is going to reverse your name. The program works by starting with last character in your name, writing it down, then writing down the previous character until it reaches the first character. Since I have no way of knowing how long your name is, this would seem to rule out a for loop.

codeView.png
function test()
{
    //function to reverse any piece of text
    var myName = window.prompt("Enter some text, e.g. your full name","");
    var x = myName.length - 1;	//determine the length of your name
    var output = "";
    while (x >= 0)
    {
       output += myName.substring(x,x+1);
       x--;		        //decrement x by 1
    }
    document.getElementById('output').innerHTML = output;
}
AttachmentSize
while-Ex1.htm1005 bytes