PFS! Computer Science

Conditional Loops
11.0. Overview

There are two things computers need to be able to do to be a computer. One is to make decisions (using an if-else statement) and the second is to loop, or repeat a set of instructions. Let's see how we can get the computer to loop.

11.1. Two types of loops

When we need to repeat a series of instructions in program, we use a loop structure. The type of structure you choose to use will usually depend on what kind of repetition you want to provide for.

Loops

A loop is a series of instructions that may be repeated over and over according to certain conditions.

In JavaScript, there are two main types of loop structures: while loops and for loops.

11.2. while loops

When we don't know in advance how many times a program should repeat something, we usually use an indefinite loop called a while loop.

The while loop is typically used when you have a loop that needs to repeat some number of times, based on a condition. "While we haven't reached the highest number, keep on counting," for example, or "While we haven't finished adding up this list of numbers, keep adding."

The while loop

The while loop is a conditional loop: it keeps repeating as long as a condition is true.

while ( Boolean condition )
{
    <statement>
    <statement>
    <statement>
}
<Statement that is not part of the loop>

11.2.1. Counting with a while loop

Perhaps the most important task that a loop can be used for is repeating something a specified number of times. Here's a while loop that counts from 0 to 9, repeating the body of the loop 10 times.

// Demonstration of counting with a while-loop
let i = 0;
while (i < 10)
{
    document.write(i + "<br />");
    i = i + 1;     
}
document.write("All done!");

The output of this loop:

0
1
2
3
4
5
6
7
8
9
All done!

There are a couple of important things to note about this loop. We've started with the variable i at 0, and when we do that, the value 10 in the statement while i < 10 indicates the number of times that the loop will repeat. That's a pattern that we'll see often. Also, the loop does run ten times as it counts from 0 to 9. Starting our counting at 0 instead of at 1, may seem strange, but this is something that computer science people do all the time, so you'll need to get used to it: the first index (or value) that we count with is almost always 0.

If you want to have your loop print out the numbers from 1 to 10 there are a number of ways you can do that. (Try to figure out what some of them are!) But as for most of the loops we use, the variable will start at index 0.

11.2.2. Interactive loops, Sentinel loops

One type of loop is an interactive loop which allows the user to interact with the instructions in a loop. Another type of loop is a sentinel loop, which continues as long as a "sentinel value" (chosen by the programmer) indicates that the loop should stop running.

This next example indicates both of those in action. This program asks people to enter their name. It will say "hello" to each person who enters a name until the empty string ("") is entered, where "" is the sentinel value for the loop.

let name = prompt("Enter your name: ");
while (name != "")
{
    alert("Hello " + name);
    name = prompt("Enter your name: ");
}
document.write("All done!");

Here, the sentinel value that will end the loop is the empty string "". As long as name doesn't have the value "", the loop will continue to run, saying "Hello" using every name that is entered. Once no value ("") is entered, the boolean expression becomes false and the body of the loop is not executed. Instead, execution proceeds to the line below the body of the loop.

Sample output:

Enter your name: Richard
Hello Richard
Enter your name: David
Hello David
Enter your name: Amanda
Hello Amanda
Enter your name: Claudine
Hello Claudine
Enter your name: ([Enter] is pressed with no value entered)
All done!

A sentinel value can be used in lots of different applications. One common example is playing a game. The program will play a game, then ask the user if they want to play again. As long as the user doesn't enter the sentinel value of "No" (or "Quit", etc.), the game loop keeps repeating.

11.3. Activity: NumberGuessingGame

Write a program...

Write a program that plays a number guessing game with the user. The program should ask the user if they'd like to play a guessing game. If the user wants to, the program picks a random number between 1 and 10 inclusive, and the user has three chances to guess the number. After each guess, the program tells the user if they got it right, if the guess was too high, or if the guess was too low. After the user has guessed the number or the user has had three guesses, whichever comes first, the guessing game is over. The program should then ask the user if s/he wants to play again.

If you're working on this problem on your own, you might want to get some advice on how to go about developing your program here.

Show/hide development steps

  1. Write an initial sentinel loop asking user if they want to play a game. If 'y', play the game (insert a pass statement in place of the body), then ask if they want to play again. Note that we're not writing the body of the game yet, we're just getting the "play again" loop set up.
  2. add goodbye message for after they don't want to play anymore
  3. develop basic game:
    1. Make up a random number between 1 and 10
    2. Get the user's guess
    3. Tell them whether they got it right or not
  4. This is just a one-number guessing game. We want to set it up so that they can have three guesses before the game is over.
  5. multiple-guessing code:
    1. Set up another while loop that counts how many times they've guessed, and we'll only give them 3 guesses. We need a new variable to keep track of the guessNumber
    2. Give a hint as to whether we guessed too high or too low
    3. Need to stop asking them for guesses if they got it right--expand conditional to while (guessNumber < 4 and theGuess != theNumber):