n301/cs19loops
n301.tplt
Loops

Allows certain parts of code to repeat based on the status of a condition
The while statement.
The while statement checks the condition and repeats the code if the condition is TRUE.
Sentry variables and Initialization
Start by creating a variable
Giving the variable an initial value is initializing the variable
Variables used in loops are often known as sentry variables
Math Quiz
Ask the user a simple math question. Continue asking the question until the user gets the answer correct.
Preventing Endless Loops
Inside a loop, we MUST ensure that there is some way of exiting the loop
We have to make it possible for the sentry variable to change values
Example
var stillRacing = "Y";
while (stillRacing == "Y"){
alert("zooming around the track");
//forgot to check if we are still racing!!!
}// end while
alert ("Nice race!!");
This program will go on FOREVER!!!
Endless Loops
The condition statement checks to see if the condition is TRUE
In the previous example, the condition is true
Because the condition is true, the body of the loop still thinks we are "zooming around the track"
Whenever you make a loop, it is your obligation to ensure that the sentry variable is changed so it is possible to exit the loop
The For Loop
Variation of the loop we have already used
Difference - we have added a counter
Needs four pieces of information:
- name of counting variable
- starting value of the variable
- ending value of the variable
- how to increment the variable
For Loop
The for statement needs three parts:
1. initialize the variable
2. a condition
3. how to increment the variable
Once the loop is set up, we don't have to worry about it in the body - it automatically increments
Ten Lap Race
Simulate a race with a program that says "now on lap: " for ten laps.
Backwards Race
Write a program that goes from ten to one
Mad lib
Try this one on your own.
Ask the user for a number of words (favorite color, name of a person, adjective). Use these words in a story.