Free for students · Ad-free · WCAG 2.1 AA Compliant · Accessibility

while Loops

Lesson ~10 min read 8 MCQs

In simple terms: 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.

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];
This diagram shows a flowchart for a while loop. It starts, then a diamond-shaped decision node asks "Is condition true?". If yes, the flow moves to two rectangular boxes, "Execute Loop Body" and "Update loop variable," which then loops back to the decision node. If no, the flow moves to "Continue with rest of program" and then ends.
The while loop acts as a gatekeeper, checking the condition before every iteration.

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:

  1. 1
    Initialization
    You need to set up your variables before the loop starts. This is like setting up the initial state of the world.
  2. 2
    Condition
    The Boolean expression that gets checked before each loop iteration.
  3. 3
    Update
    Something 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:

  1. count starts at 10.
  2. The loop asks: Is count > 0? Is 10 > 0? Yes, it's true.
  3. The loop body runs: It prints 10. It then updates count to 9.
  4. The loop goes back to the top. Is 9 > 0? Yes, true.
  5. It prints 9, updates count to 8.
  6. ...This continues until...
  7. count is 1. The loop asks: Is 1 > 0? Yes, true.
  8. It prints 1, updates count to 0.
  9. The loop goes back to the top. Is 0 > 0? No, this is false!
  10. 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 iteration
    Does it start with the right value?
  • Last iteration
    What is the last value that makes the condition true? What happens on that iteration?
  • After the last
    What 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.

Tracing the rocket countdown from 3 to 0.

See it in action

Java Code

      
      
Condition Check
Variables
Console Output

      
Step 0 / 0

Worked examples

Let's walk through a couple of problems to see how while loops work in practice.

Example 1

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:

  1. 1
    Identify the repetition
    The 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 while loop is a perfect fit.
  2. 2
    Set 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;
  3. 3
    Determine the condition
    The loop should continue while her savings are less than the goal.
    while (currentSavings < goal) {
      // ... keep saving ...
    }
  4. 4
    Define 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++;
  5. 5
    Put 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.

Example 2

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:

  1. 1
    Identify the repetition
    We need to check each character, one by one, until we either find an 'a' or run out of characters.
  2. 2
    Initialization
    We 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;
  3. 3
    Determine the condition
    This 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 ...
    }
  4. 4
    Update
    The only thing we need to do if we haven't found 'a' is to move to the next character.
    index++;
  5. 5
    Put it all together and handle the result
    After 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 if statement 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);
    }
Choosing the correct operator prevents off-by-one errors.
Visualizing the search for the first 'a' in a string.

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.

Tracing the Doubler problem to see when it exceeds 100.