Lesson 11: While Loops
This lesson demonstrates how a slight manipulation of a conditional statement can allow for the creation of a new and powerful tool in constructing programs, a while loop. Students are introduced to a while loop by analyzing the flow chart of a conditional statement in which the "true" branch leads back to the original condition. Students design their own flowcharts to represent a real-world situation that could be represented as a while loop, and they learn how to recognize common looping structures, most notably infinite loops. Students then move to App Lab, creating a while loop that runs exactly some predetermined number of times. While learning about creating while loops, students will be introduced to many of the common mistakes early programmers make with while loops and will be asked to debug small programs. They finally progress to putting if statements inside a while loop to count the number of times an event occurs while repeating the same action. This activity will recall the need for counter variables and foreshadows their further use in the following lesson.
while loops are the most primitive type of loop. The for loop, which students used in a very basic form during turtle programming, is just a more specific case of a while loop. while loops repeat a set of steps until a certain condition is met. Thus, like conditional statements, while loops use boolean expressions to determine if they will run and how many times. One of the biggest problems a programmer can run into with a while loop is to create an infinite loop. There are a couple different defensive programming strategies introduced in this lesson to help prevent infinite loops.
Getting Started (10 Minutes)
Activity (60-80 Minutes)
Wrap-up (10 Minutes)
Students will be able to:
- Explain that a while loop continues to run while a boolean condition remains true.
- Translate a real-life activity with repeated components into a form that could be represented by a while loop.
- Analyze a while loop to determine if the initial condition will be met, how many times the loop will run, and if the loop will ever terminate.
- Write programs that use while loops in a variety of contexts.
- Decide whether to use the flow charts activity or not
- Print an (Optional) Flowcharts with While Loops - Activity Guide for each student.
- Review Levels in Code Studio
For the Teacher
For the Students
- (Optional) Flowcharts with While Loops - Activity Guide
- Iterate - To repeat in order to achieve, or get closer to, a desired goal.
- while loop - a programming construct used to repeat a set of commands (loop) as long as (while) a boolean condition is true.
Getting Started (10 Minutes)
Following a looping flowchart
Introduce the structure of a while loop by demonstrating how a conditional statement that “loops” back on itself can be used to repeatedly execute a block of commands.
Either by writing it on the board or displaying it on a projector, display the following flowchart. Feel free to substitute your own example.
Ask students to follow the "instructions" in the diagram and then wait quietly once they are done.
Have students share their results with one another. They should each have a sheet of paper that contains 5 tally marks. Once they’ve shared their responses, ask them to discuss the following prompts in small groups:
- How is the flowchart we just saw similar to a normal conditional (or if statement)? How is it different? How do these differences change the results of the flowchart?
Once students have had an opportunity to share with their groups, open the discussion to the class. The most significant points to draw out are:
- This conditional statement loops back on itself. As a result, the conditional might be evaluated multiple times.
- As a result, the same command is running multiple times.
The structure we just explored is called a “while loop.” When you look at the flowchart, you can see that we “loop through” a command as long as, or “while,” a condition is true. while loops are a way we can easily represent a process that includes many repeated steps.
Once you develop an eye for them, you'll start to notice while loops all around you. Many activities that require repeated action are done "while" a condition is true.
Activity (60-80 Minutes)
(Optional) Flowcharts with while Loops
This is an optional unplugged activity. You may skip to app lab if you don't think it would be useful to you or your students.
It may also be something to come back to after writing code to reinforce the concepts.
Distribute: (Optional) Flowcharts with While Loops - Activity Guide to each student.
- Students will be reminded of the components of a flowchart and shown a couple of examples of real-life while loops.
- After determining how many times these loops will run, they will develop a real-life while loop of their own.
Once students have created their own real-life while loop, they should exchange with a partner. They should be looking for:
- Whether the while loop is properly structured
- What the while loop accomplishes
- How many times the while loop runs (It might not be possible to know exactly.)
Discuss the results of this exchange as a class, keeping the primary focus on whether everyone is properly structuring their loops. These early activities are primarily designed to get students familiar with the structure of a while loop. Common misconceptions include:
- Writing the condition on which the while loop should stop rather than continue.
- Not including steps in the while loop that will make the condition false at some point (i.e., creating an infinite loop)
The final two while loops on the worksheet are written with code and ask students to write what output that program would generate. They will likely need to keep track of the values generated by the program on their paper, in addition to the output. Encourage them to do so. The primary ideas foreshadowed here are:
There is no need to get into the details of counters or infinite loops here. Students will see them throughout the levels, but a quick comment pointing out these two ideas may help make connections between this activity and what students will see in their programs.
- Counters: Variables that count how many times a while loop has run, also called iterators, can be used to control the number of times a while loop runs.
- Infinite Loops: The final example in this activity guide produces an “infinite loop.” This means that the computer (or person implementing the algorithm) will cycle through a set of commands forever, because the while loop condition is always true. Infinite loops are almost always undesirable, but they can be deceptively easy to create by mistake. Use the last portion of this activity to call out the fact that this is an infinite loop, that it is a very real possibility to make one in a program, and that they will have to be careful when making while loops since, as this example shows, it is fairly easy to create an infinite loop which prevents the rest of your program from running.
App Lab: while loops
Now that students have some background with the structure of while loops, they will move to Code Studio where they will program with them.
Wrap-up (10 Minutes)
while loops exit ticket
Students can summarize their understanding of while loops. Students will have more opportunities to use these skills tomorrow, so this is primarily an opportunity to make sure students have an accurate understanding of what a while loop is and how it works.
- "In your own words, describe how a while loop works. Explain two things to pay attention to when creating while loops. In your response, justify why the name "while loop" accurately describes the behavior of this new programming construct."
Students may discuss this question in small groups before sharing as a class. Students’ answers may vary but will likely include:
- It repeats a set of commands.
- It continues to run “while” a boolean expression is true.
- It is called a loop because it “loops through” a set of commands.
- They may mention that visually it looks like a loop when shown in a flowchart.
- Things to pay attention to when programming while loops:
- Something inside the while loop has to update the variable in the condition so the while loop will stop
- while loops may never run if the condition begins as false
- while loops can become infinite if the condition never becomes false
- Off-by-one errors are common with while loops
while loop uses a boolean condition to repeatedly run a block of code. It checks the expression, and if it is true it runs the block of code contained within it. This process of checking the condition and running the block of code is repeated as long as the boolean condition remains true. Once the boolean expression becomes false it will stop.
We are going to start exploring a
while loop by modifying the condition on which a
while loop runs and using
console.log to ensure it is correctly evaluating its condition.
- Starter code is provided which creates a
whileloop that repeatedly moves the turtle around the screen.
- Add a
console.logcommand inside the loop after
numis assigned a random number. This way you can see the value the loop is based on.
- Run the program a couple times and look at the results.
- Change the condition for the
whileloop to check if the variable
numis less than 90. Your output might look like the example below.
Infinite while Loops
while loops run until their condition becomes false, which raises an interesting question. What happens if the condition never becomes false? In these cases the program enters what is called an infinite loop over the commands in the
while loop, and it never reaches the rest of your program. We normally avoid infinite loops in our programs, but let's try it out to see what happens.
- Starter code is provided which creates a
whileloop to move the turtle around the screen.
- Change the
whileloop condition to something that will always be true. The easiest way to do this is to change 50 to be a number that randomNumber will never generate such as 200.
- Run the program. Notice that it will never stop running. You may even get an error from your browser.
- Hit reset to stop it. Your computer may actually stop running as you expect if you let an infinite loop run for too long. It's possible you may even need to close the browser window and reload the page. If you hit reset early enough you can usually avoid this problem.
- Find a condition using
>that will also cause an infinite loop.
Changing if to while
How many times would we have to roll a die before it comes up as a 6? In the program you're about to see, we simulate rolling a die (generating a random number between 1 and 6) in order to answer this question.
Starter code is provided which re-rolls a die once if the first roll is not a 6.
if statement to a
while loop so the program will keep rolling the die while the current roll is not a 6.
* Hint: The easiest way to do this is to change the text from
Run the program to test out the change.
Debug Console: Variable Values
Up until now, if we wanted to find out the value of a variable at some point in the execution of a program, we've used
console.log. That is still going to be a great strategy but the Debug Console can do even more for us!
Check this out: We can check the value of a variable in real time (as our program executes) by typing its name into the prompt within the Debug Console and hitting "enter". This is another powerful tool for debugging your programs.
Run the program.
Use the Debug Console to check the ending value of
num. You can do this by typing num in the Debug Console and hitting enter!
Check out the new Debug Commands toolbox that has appeared next to the Debug Console! These powerful tools allow us to pause a program at a certain point while it’s running and then execute lines one at a time.
Using these tools we can investigate the state of variables and other elements of the program at any point, mid-execution. This makes it much easier to see what’s happening while the programming is actually running!
In order to use the debug commands, you first have to indicate which line you want the program to pause at. This is called adding a “breakpoint” (see animation below).
- Add a breakpoint on the line where the
whileloop starts. (Just click the line number.)
- Use the button to execute each line one at a time.
- Each time you hit the breakpoint, use the console to check value of
- NOTE: If you hit it will "continue" executing the program normally, unless of course it hits another breakpoint.
In order for a
while loop to stop at some point, the code inside the loop must change something about the state of the program - usually the value of a variable - so that eventually the boolean expression becomes false. Otherwise you'd have an infinite loop!
Starter Code: The starter code runs an infinite loop.
Run the code to see the problem in action. Remember to hit the reset button to stop the infinite loop.
Add code inside the
while loop which will update the variable
num so that the condition will eventually become false.
* TIP: you can use the debugging tools if you think they would be helpful.
Printing Before the Loop Starts
Sometimes our code will be doing the right thing but we won't be able to tell because of the way we are printing values. We need to make sure we print all the values we are interested in.
This program should write all the values of
num to the screen as it runs; however it misses one - the first one generated.
- Run the program a few times and notice that sometimes it just prints "Done." and nothing else, even though a number was generated. The first value of
numnever gets displayed.
- Add a
writestatement before the loop to print the first number.
- Hint: Look at the two times
numis assigned a value. Which one isn't being displayed?
We have seen that loops can run infinitely. On the last level we saw that there is also the chance that the loop never runs at all! If the condition of the
while loop starts out false then the loop will never run.
We fixed this problem in the last exercise by displaying the value of
num in two places: before the loop and in the loop. Duplicating code is generally a bad strategy, so the question is: can we be a little clever and get into the loop without missing any values? The answer is yes.
The solution is to initialize the values used in our boolean expression so that we are certain it will evaluate to true the first time the loop checks it. For example, if your loop condition is:
while (num != 6) you could initialize
num to anything other than 6 and you'd know that you get into the loop.
If you use this technique though...
1. You need to make sure you set the value of
num right away inside the loop.
2. You probably want to use a nonsense value like -1, so that if you ever see that displayed it will be obvious something is wrong and be easier to debug.
- Starter code is provided which creates a
whileloop that never runs.
- Run the program once to see that the loop is never entered.
- Fix the problem by changing the initial value of
numto a nonsense value such as -1.
Printing After Setting Value
We started trying to remove the duplicate code we had on the last level by initializing a variable to a nonsense, or "dummy," value that would still ensure we entered the loop.
In the code provided, not every number is going to display. However, this time we want to try not to add code to fix the problem, since duplicate code is inefficient.
Starter Code: The code is completely functional except that it does not print one of the numbers it's supposed to. In addition we don't want it to print the dummy variable of -1. Hint: What should be the last number that prints every time this program runs?
Run the program to see the behavior.
Fix the code so that it prints all the values of
num. Hint: You don't need to add any code. Just switch the order of the code you have now!
Boolean Operators in while Loops
We can create compound boolean expressions to control our
while loops just like our
if statements. Let's try using boolean operators in our
while loop condition.
Right now this code rolls two dice as long as either one of them is less than 3. Modify the condition so that it keeps rolling as long as both are less than 3.
HINT: To say that both dice are less than 3 the boolean expression must say: if die1 less-than 3 AND die2 less-than 3...
Expressing Stopping Conditions: "Until Loops"
It is often more natural to think about looping in terms of when the loop should end rather than when it should continue. For example you might say "keep going down the road until you see the gas station" or "keep calling until you get through to someone." You might think of these as "until loops" rather than "while loops," since we want the loop to continue until a condition is true rather than while a condition is true.
while loops so that you can use them in programs. An "until loop" runs until a condition is true, as opposed to a while loop which runs as long as a condition is true. That means an until loop is the logical inverse of a while loop - it runs as long as the condition is false. The table below shows how you can use the NOT (
! ) operator to translate stopping conditions into
while loop conditions.
|Expressed as Stopping||Expressed as Until Loop||Expressed as While Loop|
|Stop once you reach the gas station||Keep going until you reach the gas station||Keep going while you have NOT reached the gas station|
|Stop calling when you get through to someone||Keep calling until you get through to someone||Keep calling while you have NOT gotten through to someone|
|Note how we can use the NOT operation to find the logical inverse (or opposite) of the condition from our "until loop" to create a
Starter code is provided that repeatedly rolls two dice and writes their values to the screen. Careful: before you edit this code it creates an infinite loop.
- Use the technique above to modify this code so that the loop stops when both dice are 5 or greater.
- Try it out and experiment. You should exit the loop the first time both dice have values greater than or equal to 5 displayed.
Writing a Loop From English
Alright it’s your turn. Can you translate the English into code? This problem also involves an "until loop" problem.
Take this statement in English and translate it into code:
“Write a program that simulates the rolling of two dice. Keep rolling the dice UNTIL the sum of the dice is either a 7 OR an 11." Your program should display the results of each roll.
NOTE: this one is a little tricky. Hint: In English we sometimes say "or" when in cold hard logic we mean "and".
Here is a sample output:
Debugging: Complex Logic
In this challenge you need to find and fix a bug in a program that simulates rolling one die.
The given code accidentally loops infinitely, so something must be wrong with the condition. Can you figure out how to fix it?
Fix the condition so that it keeps rolling the die as long as the value is not a 2 or a 3.
Hint: Think about other ways you can express this idea in English.
Repeat Specific Number of Times
Instead of writing code that makes the loop run a random number of times, we can control the
while loop by changing the variable used in the boolean expression differently. Let’s try just printing a string 5 times.
- Starter Code: Right now the code prints a string "Hi" twice.
- Change the code so that it prints the string "Hi" 5 times.
- Notice how
countis being re-assigned each time through the loop.
As programmers we are always looking for more concise ways to write code. It is so common to add 1 to a variable such as in
count = count + 1 that there is actually a shorthand for it.
Introducing the ++ Operator
You can write
count++ to add 1 to
count++ does the exact same thing as
count = count + 1!
In fact the computer turns
count = count + 1 behind the scenes - it really is just a convenient shorthand.
Note: This is more of a programmer style choice so if you want to write your code using
count = count + 1 instead there is nothing wrong with that!
- Change the code to use
count = count + 1. (You'll need to be in text mode to do this.)
Misconception Alert: You don't need to write
count = count++ - the computer is doing the assignment for you.
++ Has a Friend! Introducing --
As you may have guessed, just as we can write
count = count + 1 as
count++ we can also write
count = count - 1 as
Let’s write a program that counts down from 10 down to 1.
Starter Code: The current program counts up from 1 to 10.
Change the code to use
count--to count down from 10 to 1. You will need to:
- Change the looping condition.
- Change the initial value assigned to
Introducing += and -= Operators
Sometimes you want to add or subtract something other than 1 from the current value of a variable. If you wanted to add or subtract 3 for example, such as:
count = count + 3 or
count = count - 3,
-- wouldn’t help.
It turns out this is pretty common as well so there is actually a shorthand version of
count = count + 3.
We can use the
-= operator to add or subtract any value we want to the current value of a variable.
So, the shorthand versions of
count = count + 3 and
count = count - 3 would be:
count += 3
count -= 3
Notice that these 3 statements:
count = count + 1,
count += 1 all do exactly the same thing!
Which one you use as a programmer is your choice, and in the future you can use either version, but try out the new operator here.
- Change the code to use
count += 3instead of
count = count + 3so the program will still count up by 3. (You'll need to be in text mode to do this.)
(You'll get to try out
-= on the next level.)
Try Out the -= Operator
-= operator works almost identically to
+=, but instead it subtracts the value provided from the variable. Let's use this operator to create a loop that counts down from 30 by 3's.
- Change the code to use
-=to count from down from 30 to 0 by 3's.
Defensive Loop Conditions
Take a look at the starting code. Instead of counting by 3's we had decided to count by 4's.
But this will run us into a problem. Can you see why?
We wanted to stop counting at 30, but when you count by 4 you will actually never hit 30. It would go... 24, 28, 32, 36... What we really want to do is stop when the number is greater than 30. This is an important defensive programming strategy. Make the condition catch more cases than you think you need so that if for some reason something does not go exactly as you planned it will hit the stop condition and not go infinitely.
- Change the loop condition to prevent the infinite loop and stop counting once the count is past 30.
Using an if Statement In a Loop
A common thing to do is to use variables to keep track of some sort of count. When used in a loop we count things very quickly.
Scenario: If you roll a pair of dice, rolling a 12 (two sixes) is rare. How rare? If you were to roll a pair of dice 1,000 times, on average, how many times would it come up as 12?
To figure this out, we could write code to run an experiment. It would go something like this:
Make a loop that simulates rolling a pair of dice 1,000 times.
Inside the loop, add an
if statement: if die1 + die2 == 12, then add 1 to a counter.
* After the loop, display the result.
The starter code sets up the whole experiment for you, except it doesn't count the number of 12's rolled - that's your job.
Run the code to see what the experiment does.
ifstatement inside the loop to check if the sum of the dice is equal to 12, and add 1 to
Once the loop has completed, display the number of times the sum was 12.
Note: If you remove (or comment out) the
console.log statement that displays every roll of the dice, the experiment will speed up A LOT! You could do tens of thousands of dice rolls in a matter of seconds.
Computer Science Principles
3.1 - People use computer programs to process information to gain insight and knowledge.
3.1.1 - Use computers to process information, find patterns, and test hypotheses about digitally processed information to gain insight and knowledge. [P4]
- 3.1.1A - Computers are used in an iterative and interactive way when processing digital information to gain insight and knowledge.
4.1 - Algorithms are precise sequences of instructions for processes that can be executed by a computer and are implemented using programming languages.
4.1.1 - Develop an algorithm for implementation in a program. [P2]
- 4.1.1A - Sequencing, selection, and iteration are building blocks of algorithms.
- 4.1.1B - Sequencing is the application of each step of an algorithm in the order in which the statements are given.
- 4.1.1C - Selection uses a Boolean condition to determine which of two parts of an algorithm is used.
- 4.1.1D - Iteration is the repetition of part of an algorithm until a condition is met or for a specified number of times.
- 4.1.1H - Different algorithms can be developed to solve the same problem.
4.1.2 - Express an algorithm in a language. [P5]
- 4.1.2A - Languages for algorithms include natural language, pseudocode, and visual and textual programming languages.
- 4.1.2B - Natural language and pseudocode describe algorithms so that humans can understand them.
- 4.1.2C - Algorithms described in programming languages can be executed on a computer.
- 4.1.2D - Different languages are better suited for expressing different algorithms.
- 4.1.2E - Some programming languages are designed for specific domains and are better for expressing algorithms in those domains.
- 4.1.2F - The language used to express an algorithm can affect characteristics such as clarity or readability but not whether an algorithmic solution exists.
- 4.1.2G - Every algorithm can be constructed using only sequencing, selection, and iteration.
5.2 - People write programs to execute algorithms.
5.2.1 - Explain how programs implement algorithms. [P3]
- 5.2.1A - Algorithms are implemented using program instructions that are processed during program execution.
- 5.2.1B - Program instructions are executed sequentially.
- 5.2.1C - Program instructions may involve variables that are initialized and updated, read, and written
- 5.2.1D - An understanding of instruction processing and program execution is useful for programming.
- 5.2.1I - Executable programs increase the scale of problems that can be addressed.
- 5.2.1J - Simple algorithms can solve a large set of problems when automated.
- 5.2.1K - Improvements in algorithms, hardware, and software increase the kinds of problems and the size of problems solvable by programming.
5.4 - Programs are developed, maintained, and used by people for different purposes.
5.4.1 - Evaluate the correctness of a program. [P4]
- 5.4.1B - Duplicated code can make it harder to reason about a program.
- 5.4.1E - Locating and correcting errors in a program is called debugging the program.
- 5.4.1F - Knowledge of what a program is supposed to do is required in order to find most program errors.
- 5.4.1G - Examples of intended behavior on specific inputs help people understand what a program is supposed to do.
- 5.4.1H - Visual displays (or different modalities) of program state can help in finding errors.
- 5.4.1K - Correctness of a program depends on correctness of program components, including code blocks and procedures.
- 5.4.1L - An explanation of a program helps people understand the functionality and purpose of it.
- 5.4.1M - The functionality of a program is often described by how a user interacts with it.
5.5 - Programming uses mathematical and logical concepts.
5.5.1 - Employ appropriate mathematical and logical concepts in programming. [P1]
- 5.5.1D - Mathematical expressions using arithmetic operators are part of most programming languages.
- 5.5.1E - Logical concepts and Boolean algebra are fundamental to programming.
- 5.5.1F - Compound expressions using and, or, and not are part of most programming languages.
- 5.5.1G - Intuitive and formal reasoning about program components using Boolean concepts helps in developing correct programs.
CSTA K-12 Computer Science Standards (2017)
AP - Algorithms & Programming
- 3A-AP-15 - Justify the selection of specific control structures when tradeoffs involve implementation, readability, and program performance and explain the benefits and drawbacks of choices made.