while Loops
Master indefinite iteration in Java: learn how while loops repeat code as long as a Boolean condition remains true.
What Is a Loop?
A loop is a control structure that repeats a block of code multiple times. Instead of writing the same statement over and over, a loop automates the repetition for you.
Anatomy of a while Loop
Execution Flow
Formal Syntax in Java
while vs for
| while loop | for loop | |
|---|---|---|
| Init location | Before the loop | Inside the header |
| Condition | In the parentheses | In the header (middle) |
| Update | Inside the body | In the header (end) |
| Best for | Unknown iterations | Known iterations |
| Risk | Easier to forget update | Update always visible |
Step-by-Step Approach
Example 1: Sum of Integers
Calculate the sum \(1 + 2 + 3 + \dots + n\) using a while loop.
Example 2: Sentinel Value Loop
Read user input until a sentinel value of -1 is entered. This is a classic use case where the number of iterations is unknown.
Example 3: String Processing
Count the number of vowels in a String using a while loop with .charAt().
Tracing a Loop
| Iteration | x (before) | x (after x *= 2) | \(x < 16\)? |
|---|---|---|---|
| 1 | 1 | 2 | true |
| 2 | 2 | 4 | true |
| 3 | 4 | 8 | true |
| 4 | 8 | 16 | false |
The Dreaded Infinite Loop
An infinite loop occurs when the condition never becomes false. The program freezes or runs forever.
Off-by-One Errors
An off-by-one error happens when your loop executes one too many or one too few times. This is the most common loop bug.
Common Mistakes
Key Concepts Summary
| Concept | Description |
|---|---|
| Condition | Boolean expression checked before each iteration |
| Body | Code that executes when condition is true |
| Update | Statement that changes the loop variable |
| Infinite loop | Condition never becomes false: program hangs |
| Off-by-one | Loop runs one too many or too few times |
| Sentinel | Special value that signals the loop to stop |
| Zero iterations | If condition is initially false, body never runs |
Question 1 of 5
Consider the following code segment:
int x = 1;
while (x < 10) {
x += 3;
}
System.out.println(x);
What is printed as a result of executing the code segment?
Question 2 of 5
Consider the following code segment:
int count = 0;
int num = 128;
while (num > 1) {
num /= 2;
count++;
}
System.out.println(count);
What value is printed?
Question 3 of 5
Which of the following will cause an infinite loop?
Question 4 of 5
Consider the following code segment:
int a = 0;
int b = 1;
while (b < 20) {
int temp = b;
b = a + b;
a = temp;
}
System.out.println(b);
What value of b is printed?
Question 5 of 5
Consider the following code segment:
String s = "banana";
int i = 0;
int count = 0;
while (i < s.length()) {
if (s.charAt(i) == 'a') {
count++;
}
i++;
}
System.out.println(count);
What value is printed?