Loops repeat a block of code. A while loop checks a condition first. As long as the condition is true, Java runs the loop body, then goes back and checks the condition again.
Basic while structure
A stable while loop usually has three parts:
- Initial value: prepare the loop variable before the loop starts.
- Condition: decide whether the loop should continue.
- Update: change the loop variable inside the loop.
int i = 1;
while (i <= 5) {
System.out.println("In loop: i = " + i);
i++;
}
System.out.println("After loop: i = " + i);Output:
In loop: i = 1
In loop: i = 2
In loop: i = 3
In loop: i = 4
In loop: i = 5
After loop: i = 6A while loop checks before it runs. That means the loop body may run many times, or it may run zero times.
Step through a while loop
Execute the program one line at a time. The blue line is next; variables and output update on the right.
01int i = 1;02while (i <= 5) {03 System.out.println(i);04 i++;05}06System.out.println(i);
>>>
KNOWLEDGE QUIZ
Accumulation and averages
Loops often work with an accumulator variable. The program below reads the heights of 5 people and computes the average height.
Scanner scanner = new Scanner(System.in);
final int NUM_PEOPLE = 5;
double total = 0;
int i = 1;
while (i <= NUM_PEOPLE) {
double height = scanner.nextDouble();
total += height;
i++;
}
double average = total / NUM_PEOPLE;
System.out.printf("Average height: %.2f%n", average);One possible run:
Enter person 1's height: 160.8
Enter person 2's height: 175.2
Enter person 3's height: 171.2
Enter person 4's height: 181.3
Enter person 5's height: 164
Average height: 170.50total += height adds the current height into the accumulated total. After the loop ends, total stores the sum of all heights.
KNOWLEDGE QUIZ
do-while and looping until a condition changes
while is useful when the number of repetitions is not known immediately. For example, you can count how many digits an integer has.
int num = Math.abs(scanner.nextInt());
int digits;
if (num == 0) {
digits = 1;
} else {
digits = 0;
while (num != 0) {
num /= 10;
digits++;
}
}
System.out.println("Digits: " + digits);One possible run:
Enter an integer: 123
Digits: 3The program handles 0 separately. If you only write while num != 0, the loop will not run for input 0, and the digit count would incorrectly become 0.
KNOWLEDGE QUIZ
Number guessing game
Another common while scenario is when the program does not know how many attempts the user will need. A number guessing game is a classic example. The program first creates a random answer, then keeps reading guesses. If the guess is too high, it prints a hint; if the guess is too low, it prints a different hint; when the guess is correct, the do-while condition becomes false and the loop ends.
(int) (Math.random() * 100) + 1 first produces a decimal from 0 (inclusive) to 100 (exclusive), converts it to an integer, and adds 1 to obtain 1–100. Math belongs to java.lang, so no import is needed.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int secret = (int) (Math.random() * 100) + 1;
int guess;
do {
System.out.print("Guess a number from 1 to 100: ");
guess = scanner.nextInt();
if (guess > secret) {
System.out.println("Too high");
} else if (guess < secret) {
System.out.println("Too low");
}
} while (guess != secret);
System.out.println("Correct!");
}
}One possible run:
Guess a number: 50
Too high
Guess a number: 25
Too low
Guess a number: 37
Too low
Guess a number: 43
Too high
Guess a number: 40
Too high
Guess a number: 38
Too low
Guess a number: 39
Correct! You guessed 7 time(s).The do-while loop reads at least one guess. Once the guess matches the answer, its condition becomes false and execution continues after the loop.
Actually play the guessing game
A random answer is chosen from 1–100. Use the hints to shrink the blue candidate range; when you guess correctly, watch break end the loop.
01Scanner scanner = new Scanner(System.in);02int answer = (int) (Math.random() * 100) + 1;03while (true) {04 int guess = scanner.nextInt();05 if (guess == answer) {06 System.out.println("Correct!");07 break;08 } else if (guess > answer) {09 System.out.println("Too high");10 } else {11 System.out.println("Too low");12 }13}
>>>
Use while to compute a reciprocal sum
Read a positive integer n and use while to compute 1 + 1/2 + 1/3 + ... + 1/n.
- Read a positive integer n.
- Use a while loop to accumulate each 1/i term.
- Print the final sum with two decimal places.
Use while to sum the digits of an integer
Peel off the digits of a positive integer and add them together.
- Read a positive integer named num.
- Use a while loop to take the last digit and add it to digitSum.
- Print the digit sum after the loop ends.