8.2  Java Script - Loops - for

Index Code Tester

OBJECTIVE

DISCUSSION

Looping Fundamentals 

for i = 0 to 10
   array[i] = i
next i

for Statement

for (i = 0; i <= 10; i++) {
    arrayX[i] = i;
};

Translation please...

for (start; continue while this is true; do this at end of loop) {

Code to do each loop ... can be multiple statements

};

Examples

for (i = 100; i > 50; i--) {
    document.write(i + "<br>");
};

for (i = 0; i <= 10; i = i + 3) {
    document.write(i);
    document.write("<br>");
};

for (i = 1; i <= 3; i++) { 
    for (j = 1; j <= 2; j++) {
        document.write("i,j = " + i + " " + j + "<br>");

    };   
};

EXERCISES

1.  Write a for-loop to display the numbers 1 to 3 in an alert one at a time.

2.  Write a for-loop to write the numbers 1 to 100 in increasing font-sizes.

3.  Write a for-loop to count down from 100 to 0 by two's while writing the numbers on a page using document.write. The page should display 100, 98, 96, ... , 0.

Note 4, 5, and 6 are related. Read them all before doing any.

4.  Write a function called assignArray(N, xArray) that accepts a number N and an empty array.  The function should add N elements to the array and assign the index of each element to the element. For example, element 0 should contain a 0, element 1 should contain a 1, and so on.

5.  Write a function displayArray(xArray) that accepts an array and writes the contents of the array to the document using document.write.

6.  Demonstrate your functions from #4 and #5 in a program.

7.  Write a function that creates a multiplication table for 1 to 9.

LINKS AND HELP

http://www.w3schools.com/js/js_looping.asp