while Loop
A while loop repeats a block of code as long as a given condition remains true. Unlike a for loop, it doesn't require a fixed count — it simply keeps checking the condition before every repetition.
1. What is a while Loop?
A while loop repeats a block of code as long as a given condition remains true. Unlike a for loop, it doesn't require a fixed count — it simply keeps checking the condition before every repetition.
2. Why is it used?
Some tasks need to repeat until something happens, but you don't know in advance exactly how many times — like asking a user to keep entering numbers until they type "0". A while loop suits this kind of open-ended repetition.
3. Real-Life Example
Think of filling a bucket with water: "While the bucket is not full, keep pouring water." You don't count exact pours in advance — you just keep going until the condition (bucket full) becomes false.
4. Syntax
javawhile (condition) { // code repeats as long as condition is true }
5. Example Program
javapublic class WhileLoopDemo { public static void main(String[] args) { int count = 1; while (count <= 5) { System.out.println("Count: " + count); count++; } } }
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 56. Key Points to Remember
- The condition is checked before the loop body runs even once — if it's false at the start, the body never runs.
- You must update the variable inside the loop yourself, or the loop may run forever.
whileis ideal when the number of repetitions isn't known beforehand.