While Loops
Sophie Anderson
7 min read
Listen to this study note
Study Guide Overview
This study guide covers iteration using while loops in Java. It explains loop structure, common issues like infinite and skipped loops, and various while loop applications (fixed repetitions, sentinel/flag control). It also discusses the break and continue statements, exception handling with try-catch blocks, and example algorithms. Finally, it provides exam tips focusing on loop logic, exception handling, and common while loop use cases.
#π AP Computer Science A: Iteration & Loops - Night Before Review π
Welcome! Let's solidify your understanding of iteration and loops. This guide is designed to be your quick, high-impact review for the exam. Let's get started!
# π Introduction to Iteration
Iteration is the process of repeating a block of code until a condition is met. We achieve this using loops.
- Two primary loop types:
whileloop: Repeats as long as a condition is true.forloop: (Covered later, but mentioned for context).- Enhanced
forloop: (Unit 6, not covered here).
# β³ while Loops: Anatomy and Function
A while loop executes a block of code repeatedly as long as a specified condition remains true.
java
// Code before the loop
while (condition) { // Condition is a boolean expression
// Loop body: Code to be repeated
}
// Code after the loop (executed when condition is false)
- Condition: A boolean expression that determines if the loop continues.
- Loop Body: The code block that is executed repeatedly.
- Exiting the Loop: The loop terminates when the condition becomes false or a
returnstatement is encountered within the loop body.
# β οΈ Potential Loop Issues
Be careful with loop conditions! Incorrect conditions can lead to infinite loops or skipped loops.
#βΎοΈ Infinite Loops
- Occurs when the loop condition always evaluates to
true. - Example: Forgetting to update a counter variable.
- Avoid at all costs! Can crash your program.
- Emergency Exit: Use
Ctrl + Cto stop an infinite loop.
#π« Skipped Loops
- Occurs when the loop condition is always
false. - The loop body is never executed.
- Indicates a logical error in your code.
# βοΈ Common while Loop Structures
#π’ Fixed Number of Repetitions
- Uses a counter variable to control the number of iterations.
java
int i = 0; // Initialize counter
while (i < numberOfRepetitions) {
// Do something
i++; // Increment counter
}
- Increment (
i++) is crucial! Without it, you'll get an infinite loop.
#π Variable Repetitions with a Sentinel
- Loop continues until a specific input (the sentinel) is entered.
java
import java.util.Scanner;
Scanner input = new Scanner(System.in);
System.out.print("Enter names, \"***\" to stop:");
String name = input.nextLine(); // Get initial input
while (!name.equals("***")) {
// Do something with the name
name = input.nextLine(); // Get next input
}
- Initial input is taken before the loop.
- New input is taken at the end of each iteration.
#π© Variable Repetitions with a Flag
- Loop continues until a specific condition is met within the loop.
java
boolean flag = true; // Initialize flag
while (flag) {
// Do something
if (someCondition) {
flag = false; // Set flag to false to exit loop
} else {
// Keep doing stuff
}
}
- Flag is set to
trueinitially. - Flag is set to
falsewhen the exit condition is met.
# π€ The Four Loopy Questions
Use these questions to debug your loops and ensure they work correctly.
- Does my loop start right? (Initial conditions)
- Does my loop end right? (Termination condition)
- Does my loop make progress towards completion? (Loop variable updates)
- Will the method break in the middle of the loop? (Check for
returnorbreak)
# β© break and continue Statements
#break
- Immediately exits the loop, regardless of the loop condition.
java
while (true) {
// Do something
if (certainCondition) {
// Do something else
break; // Exit the loop
}
// Do something if condition not met
}
#continue
- Skips the rest of the current iteration and jumps to the next iteration.
java
int sum = 0;
for (int i = 0; i <= 10; i++) {
if (i == 4) {
continue; // Skip when i is 4
}
sum += i;
}
# π‘οΈ Exception Handling: try-catch
Exception handling makes your code robust by preventing crashes due to runtime errors.
- Exceptions: Errors that occur during program execution.
tryblock: Contains code that might throw an exception.catchblock: Handles specific exceptions thrown in thetryblock.finallyblock: Code that always executes, regardless of exceptions.
java
public static int exceptionThrower() throws InputMismatchException {
// Some code
if (conditionForErrorMet) {
throw new InputMismatchException(); // Throw an exception
}
return 1;
}
public static void exceptionHandler() {
// Some code
try {
int i = exceptionThrower(); // Call method that might throw exception
} catch (InputMismatchException i) {
// Handle InputMismatchException
} catch (Exception e) {
// Handle other exceptions
} finally {
// Code that always runs
}
}
# π‘ Algorithms Using while Loops
#β Divisibility Without Modulo
java
public static boolean divisibility(int number, int divisor) throws NumberFormatException {
if (number < 0 || divisor <= 0) {
throw new NumberFormatException();
} else if (number == 0) {
return true;
} else {
while (number > 0) {
number -= divisor;
}
return number == 0;
}
}
#π’ Extracting Digits
java
public static void returnDigits(int number) throws NumberFormatException {
if (number < 0) {
throw new NumberFormatException();
}
while (number != 0) {
System.out.println(number % 10 + " ");
number /= 10;
}
}
#π Frequency of a Condition
java
import java.util.Scanner;
public static int determineFrequencyOfEvens() {
Scanner input = new Scanner(System.in);
int number;
int frequency = 0;
System.out.println("Enter integers, 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;
}
}
#π Finding Minimum
java
import java.util.Scanner;
public static int determineMinimum() {
Scanner input = new Scanner(System.in);
int number;
int min;
System.out.println("Enter integers, 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;
}
}
#π Finding Maximum
java
import java.util.Scanner;
public static int determineMaximum() {
Scanner input = new Scanner(System.in);
int number;
int max;
System.out.println("Enter integers, 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
java
import java.util.Scanner;
public static int computeSum() {
Scanner input = new Scanner(System.in);
int number;
int sum = 0;
System.out.println("Enter integers, 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
java
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, 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;
}
}
# π― Final Exam Focus
Focus on understanding loop structures, avoiding infinite loops, and using try-catch blocks for robust code.
- Key Topics:
whileloop syntax and logic.- Loop control variables and conditions.
- Sentinel and flag-controlled loops.
breakandcontinuestatements.- Exception handling with
try-catchblocks. - Common algorithms using
whileloops (min, max, sum, average, etc.).
- Common Question Types:
- Tracing loop execution and predicting output.
- Identifying infinite loops or skipped loops.
- Writing loops to solve specific problems.
- Using
try-catchblocks to handle exceptions.
#Last-Minute Tips
- Time Management: Don't spend too long on one question. Move on and come back if time permits.
- Common Pitfalls: Watch out for off-by-one errors in loop conditions and infinite loops.
- Strategies:
- Read the question carefully and understand what is being asked.
- Write out the loop logic on paper before coding.
- Test your code with different inputs to ensure it works correctly.
Good luck! You've got this! πͺ
Continue your learning journey

How are we doing?
Give us your feedback and let us know how we can improve





