0
0
Javaprogramming~5 mins

Counter-based while loop in Java

Choose your learning style9 modes available
Introduction

A counter-based while loop helps you repeat actions a set number of times by counting each step.

When you want to print numbers from 1 to 10.
When you need to ask a user for input exactly 5 times.
When you want to add up the first 100 numbers.
When you want to repeat a task until a certain count is reached.
Syntax
Java
int counter = 1;
while (counter <= limit) {
    // code to repeat
    counter++; // increase counter
}

Initialize the counter before the loop starts.

Increase the counter inside the loop to avoid infinite loops.

Examples
This prints numbers 1 to 5, increasing i by 1 each time.
Java
int i = 1;
while (i <= 5) {
    System.out.println(i);
    i++;
}
This counts down from 10 to 1, decreasing count by 1 each time.
Java
int count = 10;
while (count > 0) {
    System.out.println("Countdown: " + count);
    count--;
}
Sample Program

This program prints "Step 1" to "Step 5" using a counter-based while loop.

Java
public class CounterWhileLoop {
    public static void main(String[] args) {
        int counter = 1;
        int limit = 5;
        while (counter <= limit) {
            System.out.println("Step " + counter);
            counter++;
        }
    }
}
OutputSuccess
Important Notes

Always update the counter inside the loop to prevent infinite loops.

You can count up or down by changing how you update the counter.

Summary

Use a counter to control how many times a while loop runs.

Initialize the counter before the loop and update it inside.

Counter-based loops are great for repeating tasks a fixed number of times.