Working with while and do while loop

5-Working with while and do while loop

๐Ÿ” Introduction to Loops in Java

In programming, we often need to execute a block of code multiple times. Writing the same statements again and again is inefficient and makes the program difficult to manage. To solve this problem, Java provides loops ๐Ÿ”„.

Loops allow us to run a block of code repeatedly based on a condition. Among different looping constructs, while and do-while loops are known as condition-controlled loops because their execution depends on a boolean condition.

Although while and do-while loops look similar, their execution flow is very different. In this article, we will explore both loops in detail with examples, tricky cases, common mistakes, and real-world usage ๐Ÿš€.


๐Ÿ” What is a while Loop in Java?

A while loop executes a block of code only when the given condition is true โœ….
The condition is checked before entering the loop body.

If the condition is false initially, the loop will not execute even once.


๐Ÿงฉ Syntax of while Loop
while(condition) {
    // code to be executed
}

๐Ÿ“ Explanation:

  • condition must be a boolean expression.
  • If the condition evaluates to true, the loop body executes.
  • If the condition evaluates to false, the loop is skipped.

โš™๏ธ How while Loop Works Internally

๐Ÿ”„ Execution Flow
  1. The condition is evaluated.
  2. If the condition is true, the loop body executes.
  3. After execution, the condition is checked again.
  4. Steps 2 and 3 repeat until the condition becomes false.
  5. Control then moves outside the loop.
โš ๏ธ Important Observation

A while loop can execute zero times if the condition is false initially.


โœ… Basic Example of while Loop

int i = 1;

while(i <= 5) {
    System.out.println(i);
    i++;
}

๐Ÿ“ Explanation:

  • i starts with value 1.
  • The condition i <= 5 is checked before entering the loop.
  • Since the condition is true, the loop executes.
  • The value of i is printed.
  • i++ increments the value of i.
  • When i becomes 6, the condition becomes false and the loop stops.

๐Ÿ“ค Output:

1
2
3
4
5

โŒ Common Mistakes in while Loop

๐Ÿšซ Forgetting to Update the Loop Variable
int i = 1;

while(i <= 5) {
    System.out.println(i);
}

๐Ÿ“ Explanation:

  • The value of i never changes.
  • The condition i <= 5 always remains true.
  • This results in an infinite loop โ™พ๏ธ that prints 1 endlessly.

๐Ÿ‘‰ Lesson: Always update the loop variable.


๐Ÿšซ Using Assignment Instead of Comparison
int x = 5;

while(x = 10) {
    System.out.println(x);
}

๐Ÿ“ Explanation:

  • x = 10 is an assignment, not a comparison.
  • The while condition must return a boolean value.
  • Java throws a compile-time error โŒ to prevent logical bugs.

โœ… Correct Code:

while(x == 10)

๐Ÿšซ Semicolon After while Condition
while(i <= 5); {
    System.out.println(i);
}

๐Ÿ“ Explanation:

  • The semicolon ends the loop immediately.
  • The loop body becomes empty.
  • The code block runs only once, outside the loop.
  • This often leads to infinite loops or confusing output ๐Ÿ˜ต.

โ™พ๏ธ Infinite while Loop

โœ… Intentional Infinite Loop
while(true) {
    System.out.println("Running...");
}

๐Ÿ“ Explanation:

  • The condition is always true.
  • The loop never stops on its own.
  • Commonly used in:
    • Servers ๐ŸŒ
    • Game loops ๐ŸŽฎ
    • Background services

โŒ Accidental Infinite Loop
int i = 1;

while(i > 0) {
    System.out.println(i);
    i++;
}

๐Ÿ“ Explanation:

  • i keeps increasing.
  • The condition i > 0 never becomes false.
  • This creates an infinite loop due to poor logic.

๐Ÿ›‘ Using break and continue in while Loop

๐Ÿ”ด break Statement
int i = 1;

while(i <= 10) {
    if(i == 5) {
        break;
    }
    System.out.println(i);
    i++;
}

๐Ÿ“ Explanation:

  • The loop runs from 1 onward.
  • When i == 5, break terminates the loop immediately.
  • Numbers 1 to 4 are printed.

๐Ÿ”ต continue Statement
int i = 0;

while(i < 5) {
    i++;
    if(i == 3) {
        continue;
    }
    System.out.println(i);
}

๐Ÿ“ Explanation:

  • When i becomes 3, continue skips printing.
  • Remaining iterations continue normally.

๐Ÿ“ค Output:

1
2
4
5

๐Ÿ” What is a do-while Loop in Java?

A do-while loop is similar to a while loop, but the condition is checked after the loop body executes.

This guarantees that the loop body executes at least once ๐Ÿ‘.


๐Ÿงฉ Syntax of do-while Loop
do {
    // code to be executed
} while(condition);

โš ๏ธ The semicolon at the end is mandatory.


โš™๏ธ How do-while Loop Works

๐Ÿ”„ Execution Flow
  1. Loop body executes first.
  2. Condition is evaluated.
  3. If true, loop repeats.
  4. If false, loop terminates.

โœ… Basic Example of do-while Loop

int i = 1;

do {
    System.out.println(i);
    i++;
} while(i <= 5);

๐Ÿ“ Explanation:

  • Code runs once before checking the condition.
  • Then the condition is evaluated.
  • Execution continues until the condition becomes false.

โš–๏ธ Difference Between while and do-while

๐Ÿ” Condition Check
  • while โ†’ before execution
  • do-while โ†’ after execution
๐Ÿ” Minimum Execution
  • while โ†’ 0 or more times
  • do-while โ†’ at least once

๐Ÿง  Tricky do-while Examples

โ— Condition is False Initially
int x = 10;

do {
    System.out.println("Hello");
} while(x < 5);

๐Ÿ“ Explanation:

  • Condition is false.
  • Still, the loop executes once.
  • "Hello" is printed exactly once.

โ™พ๏ธ Infinite do-while Loop
do {
    System.out.println("Infinite");
} while(true);

๐Ÿ“ Explanation:

  • Executes endlessly unless terminated using break.

โŒ Common Confusions with do-while Loop

๐Ÿšซ Missing Semicolon
do {
    System.out.println("Error");
} while(true)

๐Ÿ“ Explanation:

  • Missing semicolon causes a compile-time error โŒ.
  • Semicolon is mandatory in do-while.

๐Ÿ“‹ Menu-Driven Program Using do-while
do {
    System.out.println("1. Add");
    System.out.println("2. Exit");
    choice = scanner.nextInt();
} while(choice != 2);

๐Ÿ“ Explanation:

  • Menu is shown at least once.
  • Input is taken after displaying options.
  • Loop exits only when user chooses 2.
  • Perfect use case for do-while ๐Ÿ‘.

๐Ÿ”‚ Nested while Loops

๐Ÿ“Š Nested while Loop Example
int i = 1;

while(i <= 3) {
    int j = 1;
    while(j <= 3) {
        System.out.print(j + " ");
        j++;
    }
    System.out.println();
    i++;
}

๐Ÿ“ Explanation:

  • Outer loop controls rows.
  • Inner loop controls columns.
  • Inner loop completes fully for each outer iteration.
  • Produces a matrix-like output.

๐ŸŽฏ When to Use while vs do-while

โœ… Use while Loop When
  • Execution depends strictly on condition
  • Loop may not need to execute at all
โœ… Use do-while Loop When
  • At least one execution is required
  • Input validation or menus are involved

๐Ÿ Conclusion

The while and do-while loops are fundamental building blocks in Java ๐Ÿงฑ. Though they look similar, their execution behavior is very different.

Understanding when conditions are checked, avoiding common mistakes like infinite loops and misplaced semicolons, and choosing the right loop for the problem are essential skills for every Java programmer.

Master these loops, and your Java programs will become more logical, efficient, and error-free ๐Ÿš€.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *