while Loop
Pre-test loop
5 min read
The while Loop
The while loop is a pre-test loop that checks the condition before each iteration. If the condition is false initially, the loop body never executes.
Syntax
while (condition) {
// loop body
// update statement
}
ā When to Use: Use while when you don't know the number of iterations in advance, or when the termination depends on a dynamic condition.
while vs for
- for: Best when iteration count is known
- while: Best for unknown/dynamic iteration counts
- Both can be converted to each other
ā ļø Warning: Always ensure the condition will eventually become false. Forgetting the update statement causes infinite loops!
Code Examples
Basic while loop patterns
java
1// Basic while loop
2int count = 1;
3while (count <= 5) {
4 System.out.println("Count: " + count);
5 count++;
6}
7// Output: Count: 1, 2, 3, 4, 5
8
9// Sum numbers until condition
10int sum = 0;
11int num = 1;
12while (num <= 100) {
13 sum += num;
14 num++;
15}
16System.out.println("Sum 1-100: " + sum); // 5050Input validation with while loop
java
1// User input validation
2Scanner scanner = new Scanner(System.in);
3int input = -1;
4
5while (input < 0 || input > 100) {
6 System.out.print("Enter a number (0-100): ");
7 input = scanner.nextInt();
8
9 if (input < 0 || input > 100) {
10 System.out.println("Invalid! Try again.");
11 }
12}
13
14System.out.println("You entered: " + input);Sentinel-controlled loop and string processing
java
1// Read until sentinel value
2Scanner scanner = new Scanner(System.in);
3int total = 0;
4int value;
5
6System.out.println("Enter numbers (-1 to stop):");
7value = scanner.nextInt();
8
9while (value != -1) {
10 total += value;
11 value = scanner.nextInt();
12}
13
14System.out.println("Total: " + total);
15
16// Process string character by character
17String text = "Hello";
18int index = 0;
19while (index < text.length()) {
20 System.out.println(text.charAt(index));
21 index++;
22}Mathematical operations with while
java
1// Find digits in a number
2int number = 12345;
3int digitCount = 0;
4int temp = number;
5
6while (temp > 0) {
7 temp = temp / 10;
8 digitCount++;
9}
10System.out.println(number + " has " + digitCount + " digits");
11
12// Reverse a number
13int original = 12345;
14int reversed = 0;
15temp = original;
16
17while (temp > 0) {
18 int digit = temp % 10;
19 reversed = reversed * 10 + digit;
20 temp = temp / 10;
21}
22System.out.println("Reversed: " + reversed); // 54321Use Cases
- Reading input until sentinel value
- Polling for conditions
- Game loops (until game over)
- Processing linked data structures
- Waiting for events
- Mathematical algorithms (digit extraction, GCD)
Common Mistakes to Avoid
- Infinite loop - forgetting update statement
- Off-by-one errors in condition
- Not initializing loop variable before while
- Condition never becoming false
- Using = instead of == in condition
- Modifying wrong variable in update