Subjects

Subjects

More

While Loops

Learn with content from all year groups and subjects, created by the best students.

While Loops: AP Computer Science A Study Guide



Introduction

Welcome to the magical world of loops, where computers can repeat tasks faster than you can say "iteration" five times fast! Prepare yourself for a rollercoaster ride through while loops 🚀, a fundamental concept that’s like the Energizer Bunny of programming—it keeps going and going… until you tell it to stop, that is.



What is Iteration?

Imagine you’re a robot tasked with washing dishes. Instead of washing one plate, stopping, and then restarting for the next, you could use iteration—a fancy word for repeating an action until a certain condition is met—to wash all the plates in one go. In programming, we achieve iteration with loops. There are three types of loops we love in Java: while loops, for loops, and the enhanced for loop. The latter, however, is our guest star in Unit 6, so stay tuned.



Introduction to While Loops

Let’s dive into the thrilling world of while loops. They are your basic loop-to-loop roller coasters: they keep going as long as the condition is true. Here’s the basic structure:

code before loop
while (condition) {
  do this while the condition is true
}
do this when the condition is no longer true

The condition is a Boolean statement, which means it evaluates to either true or false, like a light switch that’s either on or off. While the light switch is "on" (the condition is true), the loop keeps running. Once the light switch flips "off" (the condition becomes false), the loop stops.



Possible Issues with Loops

Loops are like DIY projects; sometimes they go hilariously wrong. You could end up with an infinite loop, which is like a TikTok binge—never-ending. Or you might have a loop that never runs, making it a complete couch potato.

Loop Condition Always True

If the loop’s condition never changes and is always true, congrats, you’ve created an infinite loop! This loop can go on forever like your granny's stories. To stop it, you’d have to manually break out of it, usually using ctrl+c in your coding environment. Trust me, you don’t want to be that coder who crashes the server with an infinite loop.

Loop Condition Always False

On the flip side, if the loop’s condition is always false, it’s like buying concert tickets but never going to the gig. The loop body never runs, resulting in inefficiencies and unnecessarily long code. Both situations should be avoided like pineapple on pizza (just kidding, if you like that sort of thing).



While Loop Structures

There are various ways you can structure your while loops, depending on how you want them to behave.

Fixed Number of Repetitions

When you know exactly how many times you want to repeat an action, use an integer as a counter. For example:

int i = 0;
while (i < numberOfRepetitions) {
  // Do something
  i++;
}

Here, i is your trusty counter, incrementing by 1 every time until it hits the number of repetitions you set.

Variable Number of Repetitions Using a Sentinel

A sentinel is like clapping your hands as a signal to stop what you’re doing. This is handy when you don't know how many iterations are needed. For instance:

import java.util.Scanner;

System.out.print("Enter names, hit enter between each one. Type 'done' to stop:");
Scanner input = new Scanner(System.in);
String name = input.nextLine();

while (!name.equals("done")) {
  // Do something
  name = input.nextLine();
}

Notice how the input check happens inside and outside the loop? It’s like checking for Wi-Fi at home and at the coffee shop.

Variable Number of Repetitions Using a Flag

A flag is used when you continue looping until a specific condition inside the loop is met. Think of it like playing hide-and-seek until someone yells, “Found you!”

boolean flag = true;
while (flag) {
  // Do something
  if (some condition is met) {
    flag = false;
  }
}


Making Sure Your Loop Works: The Four Loopy Questions

To avoid loop disasters, ask yourself these questions (inspired by Professor David Gries’s course at Cornell):

  1. Does my loop start right?
  2. Does my loop end right?
  3. Does my loop make progress towards completion?
  4. Will the method break in the middle of the loop?

It's like quality control for your loop—think of it as giving your code an annual check-up.



Break and Continue

These statements are your emergency exit signs.

Break Statement

The break statement bulldozes its way out of the loop, stopping it immediately regardless of the loop condition. It’s like pulling the fire alarm 🚨.

while (true) {
  // Do something
  if (certain condition is met) {
    // Do something else
    break;
  }
  // Do more stuff if condition not met
}

Continue Statement

The continue statement is the skip button of loops. It skips the current iteration and jumps to the next one. Imagine summing numbers 1 to 10 but skipping 4:

public static int sampleSum() {
  int i = 0;
  int sum = 0;
  while (i <= 10) {
    i++;
    if (i == 4) {
      continue;
    }
    sum += i;
  }
  return sum;
}


Try-Catch Statements and Exception Handling

When coding, especially with loops, you want your code to be as robust as a bouncer at a nightclub. This means handling errors gracefully instead of letting your program crash and burn.

Exceptions are errors that occur at runtime. With try-catch blocks, you try a piece of code. If it fails, the catch block handles the exception, preventing total disaster.

public static int exceptionThrower() throws InputMismatchException {
  // Some code
  if (conditionForErrorMet) {
    throw new InputMismatchException();
  }
  return 1;
}

public static void exceptionHandler() {
  try {
    int i = exceptionThrower();
  } catch (InputMismatchException e) {
    // Handle InputMismatchException
  } catch (Exception e) {
    // Handle other exceptions
  } finally {
    // Run this code no matter what
  }
}


Algorithms Using While Loops

Here are some cool algorithms you can create using while loops:

Finding Divisibility Without Modulo

This checks if a number is divisible by another without using modulo:

public static boolean divisibility(int number, int divisor) throws NumberFormatException {
  if (number < 0 || divisor <= 0) {
    throw new NumberFormatException();
  }
  while (number > 0) {
    number -= divisor;
  }
  return number == 0;
}

Finding the Digits in an Integer From Small to Large Magnitude

Displays digits of a positive integer:

public static void returnDigits(int number) throws NumberFormatException {
  while (number != 0) {
    System.out.println(number % 10 + " ");
    number /= 10;
  }
}

Determining Frequency of a Condition

Counts how many even numbers are in a sequence:

import java.util.Scanner;

public static int determineFrequencyOfEvens() {
  Scanner input = new Scanner(System.in);
  int number;
  int frequency = 0;
  System.out.println("Enter integers line by line. Enter 000 to end");
  try {
    number = input.nextInt();
    while (number != 000) {
      if (number % 2 == 0) {
        frequency++;
      }
      number = input.nextInt();
    }
  } catch (Exception e) {
    System.out.println("Invalid input. Terminating input sequence");
  } finally {
    return frequency;
  }
}

Determine a Minimum from Inputs

Finds the smallest number in a sequence:

import java.util.Scanner;

public static int determineMinimum() {
  Scanner input = new Scanner(System.in);
  int number;
  int min;
  System.out.println("Enter integers line by line. Enter 000 to end");
  try {
    number = input.nextInt();
    min = number;
    while (number != 000) {
      if (number < min) {
        min = number;
      }
      number = input.nextInt();
    }
  } catch (Exception e) {
    System.out.println("Invalid input. Terminating input sequence");
  } finally {
    return min;
  }
}

Determine a Maximum from Inputs

Finds the largest number in a sequence:

import java.util.Scanner;

public static int determineMaximum() {
  Scanner input = new Scanner(System.in);
  int number;
  int max;
  System.out.println("Enter integers line by line. Enter 000 to end");
  try {
    number = input.nextInt();
    max = number;
    while (number != 000) {
      if (number > max) {
        max = number;
      }
      number = input.nextInt();
    }
  } catch (Exception e) {
    System.out.println("Invalid input. Terminating input sequence");
  } finally {
    return max;
  }
}

Computing a Sum from Inputs

Calculates the sum of a sequence of integers:

import java.util.Scanner;

public static int computeSum() {
  Scanner input = new Scanner(System.in);
  int number;
  int sum = 0;
  System.out.println("Enter integers line by line. Enter 000 to end");
  try {
    number = input.nextInt();
    while (number != 000) {
      sum += number;
      number = input.nextInt();
    }
  } catch (Exception e) {
    System.out.println("Invalid input. Terminating input sequence");
  } finally {
    return sum;
  }
}

Computing an Average from Inputs

Calculates the average of a sequence of integers:

import java.util.Scanner;

public static double computeAverage() {
  Scanner input = new Scanner(System.in);
  int number;
  int sum = 0;
  int counter = 0;
  System.out.println("Enter integers line by line. Enter 000 to end");
  try {
    number = input.nextInt();
    while (number != 000) {
      sum += number;
      counter++;
      number = input.nextInt();
    }
  } catch (Exception e) {
    System.out.println("Invalid input. Terminating input sequence");
  } finally {
    return (double) sum / counter;
  }
}


Key Terms to Review

Boolean Statement: An expression that evaluates to either true or false.

Break Statement: Used in loops and switch statements to terminate their execution prematurely.

Counter: A variable that keeps track of a value, usually used to count or iterate through a loop.

Divisibility Modulo: Determining whether one number is divisible by another using modular arithmetic.

Exception Handling: A mechanism in programming to handle and manage errors.

Finally Block: Executed as part of a try-catch block, no matter what.

Flag: Acts as a signal or indicator within a program.

For Loop: Repeatedly executes a block of code for a specified number of times or until a condition is met.

Infinite Loop: A loop that repeats indefinitely, causing the program to get stuck.

Iteration: The process of repeating a set of instructions multiple times.

Loop Body: The block of code executed repeatedly in a loop.

NumberFormatException: An exception that occurs when converting a string to a numeric type, but it’s not properly formatted.

Return Statement: Used in functions/methods to specify what value should be sent back as output.

Scanner Class: Java’s built-in class that allows users to read input from various sources like the keyboard.


Happy looping and may your code always run as smoothly as a jazz saxophonist! 🎷✨

Knowunity is the # 1 ranked education app in five European countries

Knowunity was a featured story by Apple and has consistently topped the app store charts within the education category in Germany, Italy, Poland, Switzerland and United Kingdom. Join Knowunity today and help millions of students around the world.

Ranked #1 Education App

Download in

Google Play

Download in

App Store

Knowunity is the # 1 ranked education app in five European countries

4.9+

Average App Rating

15 M

Students use Knowunity

#1

In Education App Charts in 12 Countries

950 K+

Students uploaded study notes

Still not sure? Look at what your fellow peers are saying...

iOS User

I love this app so much [...] I recommend Knowunity to everyone!!! I went from a C to an A with it :D

Stefan S, iOS User

The application is very simple and well designed. So far I have found what I was looking for :D

SuSSan, iOS User

Love this App ❤️, I use it basically all the time whenever I'm studying

Can't find what you're looking for? Explore other subjects.