π2.7: while Loops
Table of Contents
π This page is a condensed version of CSAwesome Topic 2.7
β΄β΄β΄ NEW UNIT/SECTION! β΄β΄β΄
Create a blank Java program to take your class notes in for the next few lessons.
Click on the collapsed heading below for GitHub instructions ‡
π NOTES PROGRAM SETUP INSTRUCTIONS
- Go to the public template repository for our class: BWL-CS Java Template
- Click the button above the list of files then select
Create a new repository
- Specify the repository name:
CS2-Unit2PartB-Notes
- For the description, write:
Iteration/repetition (while loops, for loops)
- Click
Now you have your own personal copy of this starter code that you can always access under the
Your repositories
section of GitHub! π - Now on your repository, click and select the
Codespaces
tab - Click
Create Codespace on main
and wait for the environment to load, then youβre ready to code! - π Take notes in this Codespace during class, writing code & comments along with the instructor.
π When class ends, donβt forget to SAVE YOUR WORK! Codespaces are TEMPORARY editing environments, so you need to COMMIT changes properly in order to update the main repository for your program.
There are multiple steps to saving in GitHub Codespaces:
- Navigate to the
Source Control
menu on the LEFT sidebar - Click the button on the LEFT menu
- Type a brief commit message at the top of the file that opens, for example:
updated Main.java
- Click the small
βοΈ
checkmark in the TOP RIGHT corner - Click the button on the LEFT menu
- Finally you can close your Codespace!
While Loops
When you play a song, you can set it to loop, which means that when it reaches the end it starts over at the beginning. A loop in programming, also called iteration or repetition, is a way to repeat one or more statements. If you didnβt have loops to allow you to repeat code, your programs would get very long very quickly! Using a sequence of code, selection (ifs), and repetition (loops), the control structures in programming, you can construct an algorithm to solve almost any programming problem!
A while
loop executes the body of the loop as long as (or while) a boolean
condition is true. When the condition is false, we exit the loop and continue with the statements that are after the body of the while
loop. If the condition is false the first time you check it, the body of the loop will not execute.
Notice the while
statement looks a lot like an if
statement, but it runs more than once. The curly braces ({}
) are optional when there is just 1 statement following the condition, but required if there are more than 1 statement in the loop. In the AP exam, they will always use curly braces, which is a good practice to follow.
// The statements in an if run one time if the condition is
// is true and zero times if it is false.
if (condition) {
statements;
}
// The statements in a while loop run zero or more times,
// determined by how many times the condition is true
while (condition) {
statements;
}
Hereβs what the flow of control looks like in a Java while loop. Notice that while the condition is true, the loop body is repeated.
Three Steps to Writing a Loop
The simplest loops are counter-controlled loops like below, where the loop control variable is a counter that controls how many times to repeat the loop. There are 3 steps to writing a loop using this loop control variable as seen below in a loop that counts from 1 to 10.
π Remember these 3 steps to writing a loop:
- Initialize the loop variable (before the
while
loop) - Test the loop variable (in the loop header)
- Change the loop variable (in the while loop body at the end)
Tracing Loops
A really important skill to develop is the ability to trace the values of variables and how they change during each iteration of a loop.
You can create a tracing table that keeps track of the variable values each time through the loop as shown below. This is very helpful on the exam. Studies have shown that students who create tables like this do much better on code tracing problems on multiple choice exams.
A trace table shows the values of all of the variables each time through the loop.
Iteration 0
means before the loop. When you are tracing through code, pretend to be the computer running the code line by line, repeating the code in the loop, and keeping track of the variable values and output.
Common Errors with Loops
One common error with loops is to accidentally create an βΎοΈ infinite loop βΎοΈ. An infinite loop is one that never stops because the condition is always true.
Sometimes we will write an infinite loop on purpose like this:
while (true) {
System.out.println("This is a loop that never ends");
}
But if we create an infinite loop by accident, our program may seem to get stuck. For example look at this loop:
int i = 0;
while (i < 10) {
System.out.println(i);
}
That loop looks a lot like loops earlier in this chapter but it is actually an infinite loop. Can you see why?
The problem in this loopβand a common way to accidentally create an infinite while
loopβis that although it includes steps 1 and 2 (initializing the loop variable and testing it) it forgot step 3 and never changes the loop variable. The loop variable, i
, starts at 0
and the loop loops as long as i < 10
which will always be true because thereβs no code in the loop that changes i
. The simple fix is to add a line that increments i
:
int i = 0;
while (i < 10) {
System.out.println(i);
i++;
}
Another common error with loops is an off-by-one error where the loop runs one too many or one too few times. This is usually a problem with step 2 (the test condition) and using the incorrect relational operator <
or <=
.
Input-Controlled Loops
You can use a while
loop to repeat the body of the loop a certain number of times as shown above.
However, a while
loop is typically used when you do NOT know how many times the loop will execute. It is often used for a input-controlled loop where the userβs input indicates when to stop.
For example, in the Magpie chatbot lab on replit.com below, the while loop stops when you type in βByeβ. The stopping value is often called the sentinel value for the loop. Notice that if you type in βByeβ right away, the loop will never run. If the loop condition evaluates to false initially, the loop body is not executed at all. Another way to stop the loop prematurely is to put in a return
statement that makes it immediately return from the method.
π» In-Class Activity: Guessing Game
Acknowledgement
Content on this page is adapted from Runestone Academy - Barb Ericson, Beryl Hoffman, Peter Seibel.