While Loop


package practice;

public class WhileLoop {

    public static void main(String[] args) {

        int i = 0;

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

    }

}


Explanation

Loops are used in programming to repeat a block of code multiple times. Instead of writing the same line again and again, you can use a loop to automate repetition, which makes code shorter, cleaner, and more powerful.

How the while Loop Works:

  1. int i = 0; → Initializes the loop variable.

  2. while (i < 5) → Checks the condition before executing the block.

  3. System.out.println(i); → Prints the value of i.

  4. i++; → Increases i by 1.

  5. This repeats until the condition i < 5 becomes false (i.e., when i = 5).

Output – 

0
1
2
3
4