while Loops
Why this matters
Imagine you're running a bake sale for your school's robotics club. You raised $475! Now you have to send a personalized thank-you email to every single person who donated. You have a list of 50 names. Typing out each email would take forever. "Hi, Liam...", "Hi, Sofia...", "Hi, Jordan...". It's the same basic task, just repeated with a small change each time.
This is exactly the kind of problem where programmers get excited. Repetitive tasks are what computers are born to do. But how do you tell the computer, "keep doing this until the list is empty"? You need a way to control that repetition. That's where while loops come in. They are your tool for managing any process that needs to happen an unknown number of times, from sending those emails to running a game simulation until the player wins.
Concept overview
flowchart TD
A[Start] --> B{Is condition true?};
B -- Yes --> C[Execute Loop Body];
C --> D[Update loop variable];
D --> B;
B -- No --> E[Continue with rest of program];
E --> F[End];
Core explanation
Hey there, it's Saavi. Let's talk about one of the most powerful ideas in programming: repetition. So many problems, from simple games to complex data analysis, involve doing something over and over again. In Java, the while loop is one of our primary tools for this.
The Basic Idea: A Conditional Loop
Think of a while loop like a very persistent bouncer at a club.
- There's a rule (a Boolean condition):
age >= 21. - The bouncer checks the rule.
- If it's
true, you get to go inside and party (the loop body executes). - After you're done, you have to go back to the bouncer to get checked again.
As long as the condition is true, the process repeats. The moment the condition becomes false, the party's over, and the program moves on.
The basic structure in Java looks like this:
while (boolean_expression) {
// Code to be repeated
// This is called the loop body
}
The boolean_expression is the question the loop asks before every single iteration. If the answer is true, the code inside the curly braces {} runs. If the answer is false, the code inside is skipped entirely, and the program continues with whatever comes after the loop.
The Three Parts of a Loop
To make a while loop work correctly, you almost always need three key ingredients:
- 1InitializationYou need to set up your variables before the loop starts. This is like setting up the initial state of the world.
- 2ConditionThe Boolean expression that gets checked before each loop iteration.
- 3UpdateSomething inside the loop body must change the variable(s) used in the condition. If you forget this, you might create an infinite loop!
Let's see this in action with a countdown for a rocket launch.
// 1. Initialization
int count = 10;
// 2. Condition
while (count > 0) {
System.out.println(count);
// 3. Update
count = count - 1; // or count--;
}
System.out.println("Blast off!");
Let's trace this:
countstarts at10.- The loop asks: Is
count > 0? Is10 > 0? Yes, it'strue. - The loop body runs: It prints
10. It then updatescountto9. - The loop goes back to the top. Is
9 > 0? Yes,true. - It prints
9, updatescountto8. - ...This continues until...
countis1. The loop asks: Is1 > 0? Yes,true.- It prints
1, updatescountto0. - The loop goes back to the top. Is
0 > 0? No, this isfalse! - The loop terminates. The code inside the
{}is skipped, and the program moves on to print "Blast off!".
When the Loop Never Runs
What if the condition is false from the very beginning?
int ticketsLeft = 0;
while (ticketsLeft > 0) {
// This code will never run
System.out.println("Selling a ticket!");
ticketsLeft--;
}
System.out.println("Sold out!");
Here, ticketsLeft starts at 0. The loop condition ticketsLeft > 0 is immediately false. The loop body is never executed, not even once. The program jumps right over it and prints "Sold out!". This is a key feature of while loops: they are "pre-test" loops, meaning they check the condition before running.
The Dreaded Infinite Loop
Why does this happen? Almost always, it's because you forgot the update step.
// DANGER: INFINITE LOOP
int i = 0;
while (i < 5) {
System.out.println("This is the song that never ends...");
// Whoops! We forgot to change the value of i.
// i will always be 0, and 0 is always less than 5.
}
This program will print "This is the song that never ends..." forever (or until you force the program to stop). The value of i never changes, so the condition i < 5 is never broken. Always make sure something inside your loop is working towards making the condition false.
Off-by-One Errors
Another classic pitfall. An "off-by-one" error is when your loop runs one time too many, or one time too few. This usually comes down to using < versus <= or choosing the wrong starting value.
Let's say you want to print the numbers 1 through 5.
// Correct way
int num = 1;
while (num <= 5) {
System.out.println(num);
num++;
}
// Prints: 1, 2, 3, 4, 5
// Common off-by-one mistake
int num = 1;
while (num < 5) { // Using < instead of <=
System.out.println(num);
num++;
}
// Prints: 1, 2, 3, 4 (Oops, missed 5!)
My best advice: When you write a loop, manually trace the first and last iterations.
- First iterationDoes it start with the right value?
- Last iterationWhat is the last value that makes the condition
true? What happens on that iteration? - After the lastWhat is the first value that makes the condition
false? Does that correctly stop the loop?
Getting comfortable with while loops is about getting comfortable with this process of initialization, condition checking, and updating. Master these three parts, and you'll be able to tackle any repetitive task the AP exam throws at you.
See it in action
Worked examples
Let's walk through a couple of problems to see how while loops work in practice.
Saving for a Goal
Problem: Priya has $50 in her savings account. She wants to buy a new graphics card that costs $450. If she saves an additional $25 each week, how many weeks will it take her to afford the card?
Step-by-Step Solution:
- 1Identify the repetitionThe core action is "saving $25" and a week passing. This repeats until she has enough money. Since we don't know the exact number of weeks ahead of time, a
whileloop is a perfect fit. - 2Set up the variables (Initialization)We need to track her current savings, the goal, and the number of weeks.
double currentSavings = 50.0; double goal = 450.0; int weeks = 0; - 3Determine the conditionThe loop should continue while her savings are less than the goal.
while (currentSavings < goal) { // ... keep saving ... } - 4Define the loop body (Update)In each iteration (each week), two things happen: her savings increase by $25, and the week counter goes up by 1.
currentSavings = currentSavings + 25; weeks = weeks + 1; // or weeks++; - 5Put it all together and add the final output
public class SavingsCalculator { public static void main(String[] args) { double currentSavings = 50.0; double goal = 450.0; int weeks = 0; while (currentSavings < goal) { currentSavings += 25; // shorthand for currentSavings = currentSavings + 25 weeks++; } System.out.println("It will take Priya " + weeks + " weeks to save for the graphics card."); } }
Where students go wrong: A common mistake here is the condition. If you write while (currentSavings <= goal), the loop will run one extra time. After 16 weeks, she'll have exactly $450. The condition 450 < 450 is false, so the loop stops correctly. If you used <=, 450 <= 450 would be true, the loop would run again, and you'd get an answer of 17 weeks, which is incorrect.
Finding the First 'a'
Problem: Given a string, find the index of the first occurrence of the letter 'a'. If 'a' is not in the string, return -1.
Step-by-Step Solution:
- 1Identify the repetitionWe need to check each character, one by one, until we either find an 'a' or run out of characters.
- 2InitializationWe need an index to keep track of our position in the string. We'll start at the beginning, index 0.
String word = "database"; int index = 0; - 3Determine the conditionThis is tricky. We need to keep looping as long as two things are true:
- We haven't gone past the end of the string (
index < word.length()). - We haven't found the character 'a' yet (
word.charAt(index) != 'a'). We combine these with a logical AND (&&).
while (index < word.length() && word.charAt(index) != 'a') { // ... keep searching ... } - We haven't gone past the end of the string (
- 4UpdateThe only thing we need to do if we haven't found 'a' is to move to the next character.
index++; - 5Put it all together and handle the resultAfter the loop finishes, one of two things happened: we either found 'a', or we ran off the end of the string. We can use an
ifstatement to figure out which.// ... inside main method ... String word = "database"; int index = 0; while (index < word.length() && word.charAt(index) != 'a') { index++; } if (index == word.length()) { // If the loop finished because index reached the end System.out.println("The index is: -1"); } else { // If the loop finished because we found 'a' System.out.println("The first 'a' is at index: " + index); }
Try it yourself
Ready to try on your own? Remember to think about the three key parts: initialization, condition, and update.
Problem 1: The Doubler
Write a program that starts with a number, n = 1. Using a while loop, keep doubling n (i.e., n = n * 2) and printing its value. The loop should stop once n is greater than 100. What is the first value of n that is printed that is greater than 100?
Hint: Your loop condition should probably be while (n <= 100). What happens in each iteration?
Problem 2: Password Checker
A user needs to enter a password that is at least 8 characters long. Write a program that uses a Scanner to ask the user for a password. Use a while loop to keep asking for a password until the one they enter is 8 or more characters long.
Hint: You can get the length of a String s with s.length(). Your loop should continue while the length is less than 8.
Practice — 8 questions
In simple terms, a `while` loop is a way to tell your computer to repeat a block of code over and over, as long as a specific condition remains true.
while (boolean_expression) {
// Code to be repeated
// This is called the loop body
}
- 2.7.A: Identify when an iterative process is required to achieve a desired result.
- 2.7.B: Develop code to represent iterative processes using while loops and determine the result of these processes.
- 2.7.A.1
- Iteration is a form of repetition. Iteration statements change the flow of control by repeating a segment of code zero or more times as long as the Boolean expression controlling the loop evaluates to true.
- 2.7.A.2
- An infinite loop occurs when the Boolean expression in an iterative statement always evaluates to true.
- 2.7.A.3
- The loop body of an iterative statement will not execute if the Boolean expression initially evaluates to false.
- 2.7.A.4
- Off by one errors occur when the iteration statement loops one time too many or one time too few.
- 2.7.B.1
- A while loop is a type of iterative statement. In while loops, the Boolean expression is evaluated before each iteration of the loop body, including the first. When the expression evaluates to true, the loop body is executed. This continues until the Boolean expression evaluates to false, whereupon the iteration terminates.
flowchart TD
A[Start] --> B{Is condition true?};
B -- Yes --> C[Execute Loop Body];
C --> D[Update loop variable];
D --> B;
B -- No --> E[Continue with rest of program];
E --> F[End];
Read what Saavi narrates
(upbeat, warm music fades in and then fades to background)
Hey everyone, Saavi here. Welcome to Shrutam!
Let’s talk about something we all wish we could do: automate the boring stuff. Imagine you're running a bake sale for your school's robotics club. You raised almost five hundred dollars! Amazing. But now... you have to send a personalized thank you email to every single person who donated. Typing that out over and over would be so tedious.
This is where a programmer thinks, "I can make the computer do this!" The tool for this kind of repetitive job is a loop. Specifically, we're going to look at the `while` loop today.
A `while` loop is a simple but powerful idea. It tells the computer to repeat a block of code over and over, as long as a certain condition is true. The moment that condition becomes false, the loop stops, and the program moves on. It’s your way of saying, "Keep doing this, *while* this is true."
Let's look at a practical example. Say Priya has 50 dollars saved up, and she wants to buy a new graphics card that costs 450 dollars. She can save 25 dollars each week. How many weeks will it take her?
We can solve this with a `while` loop. We'll set up a variable for her current savings, starting at 50. The loop's condition will be: `while` her savings are less than the 450 dollar goal.
Inside the loop, we do two things for each week that passes: we add 25 dollars to her savings, and we add 1 to our week counter.
The loop will run, again and again... savings go up, weeks go up... until finally, her savings hit 450 dollars. At that point, the condition "savings are less than 450" is no longer true. The loop stops. And the value in our week counter is the answer. In this case, it's 16 weeks.
Now, one of the most common mistakes students make is creating an infinite loop. This happens when the loop's condition can never become false. In our savings example, what if we forgot to add 25 dollars to her savings inside the loop? Her savings would always be 50, which is always less than 450. The loop would run forever! So, always remember to include something inside your loop that makes progress toward stopping it.
Once you get the hang of `while` loops, you start to see opportunities to use them everywhere. They are a foundational skill, and you are totally capable of mastering them.
Keep practicing, and I'll see you next time.
(music swells and fades out)
The condition that the loop checks will never become false, causing the program to run forever and never move on.
Always double-check that something *inside* the loop's body changes the variable(s) being tested in the `while` condition.
int i = 0;
while (i < 10) {
System.out.println(i);
i++; // Don't forget this!
}
Your loop will stop one iteration too early, excluding the final value from its calculation or output.
To include the final number in a count (e.g., 1 to 10), your condition must be `count <= 10`, not `count < 10`. Manually trace the last intended run to verify your boundary.
Similar to the above, your countdown loop will stop one iteration too early. A countdown from 10 to 1 should stop after 1, not after 2.
For a countdown that includes 1, the condition should be `count >= 1`, not `count > 1`.
If you declare and initialize a variable inside the loop, it gets reset with every single iteration. The loop can never make progress towards its goal.
Always initialize accumulator variables (like counters or sums) *before* the `while` loop begins.
int count = 0; // Initialize BEFORE the loop
while (count < 5) {
// int count = 0; <-- WRONG PLACE! This would be an infinite loop.
System.out.println("Still looping...");
count++;
}
The `while` condition was `false` on the very first check. This means your initial values already satisfied the stopping condition.
Check your initial variables and the logic of your boolean expression. Are you testing for `< 0` when the variable starts at 0? That condition is immediately false.