Loops


Slides

Slides Here!


Additional Info


In Class Exercises (ICEs)

Part 1: 'Tracing' an accumulator program

Open up the file for the TraceThisAccumulatorPattern_ICE.html.  Your goal is to trace the program much like the instructor did in the slides.  You can do this on paper or on your computer (if you want to create a table in Microsoft Word open up the 'Insert' ribbon and then use the 'Table' button). 

HINT: If you want to check your answers you can add the following line into your program at the point where you want to check your work:

alert(outputString);
 

This will then cause the browser to display the value of outputString to you in an alert box (except for the newline characters (the \n characters), which will cause a line break that you can see in the alert box).

Part 2: Using the for Statement

Write a script that uses a for loop to display the numbers from 1 to 20 down the left hand side of the document.

Alter the script to display the numbers from 1 to 100, 2 to 50 by twos, 50 to 5 by fives, etc.

Part 3: Generating a List Using a for Statement

Use a for loop to generate a single string that represents an html unordered list (using the <ul> and <li> tags), where each list element is a string entered by the user into a prompt box. The user should enter 5 items to put into the list.

You will need a string variable to serve as an accumulator. Each time through the loop, you should append the string entered by the user into the prompt to the end of the accumulator variable, surrounded by <li> and </li> tags. At the end, you should put <ul> and </ul> tags at either end of the string, with the following statement:

accumulator = "<ul>" + accumulator + "</ul>"

Part 4: Using the switch Statement

Create a page with a textbox that allows the user to enter a month, along with a button to call a function named displayNumberOfDaysInTheMonth.  In the function, you should use a switch statement to display the number of days in the month entered by the user (using an on-page paragraph - do NOT use alert).  Use the switch's default case to provide a message when the user has not entered a valid month, and offer a different message if the user elected to cancel the prompt instead of submitting a month.

Note: one way to easily compare strings is to convert the user's input to lowercase, then use all lowercase month names in your switch's cases.  You may need to search online for a JavaScript function that converts a string to lowercase.