TechTorch

Location:HOME > Technology > content

Technology

Implementing Java Programs to Print Numbers Divisible by 3 Using While and Do-While Loops

April 26, 2025Technology5014
Implementing Java Programs to Print Numbers Divisible by 3 Using While

Implementing Java Programs to Print Numbers Divisible by 3 Using While and Do-while Loops

Java is a versatile programming language that has robust support for loops, making it ideal for a variety of tasks, including iterating over a range of numbers. In this article, we'll explore how to write Java programs that use a while loop and a do-while loop to print numbers between 1 and 100 that are divisible by 3.

Understanding the Problem

The task is to print the numbers between 1 and 100 that are divisible by 3. These numbers are 3, 6, 9, 12, and so on. The challenge is to implement this functionality using both a while loop and a do-while loop.

Using a While Loop

Let's first see how to achieve this using a while loop. A while loop repeats a block of code as long as the specified condition is true.

public class Main {
    public static void main(String[] args) {
        int i  1;
        while (i  100) {
            if (i % 3  0) {
                (i);
            }
            i  ;
        }
    }
}

In this code:

The variable int i 1 is declared and initialized to 1. The while (i 100) loop continues as long as i is less than or equal to 100. The if (i % 3 0) condition checks if i is divisible by 3. If true, the number is printed. The i statement increments i by 1 after each iteration.

Using a Do-While Loop

A do-while loop is similar to a while loop, but it guarantees that the loop body will run at least once, even if the condition is initially false.

public class Main {
    public static void main(String[] args) {
        int i  1;
        do {
            if (i % 3  0) {
                (i);
            }
            i  ;
        } while (i  100);
    }
}

In this code:

The variable int i 1 is declared and initialized to 1. The do { ... } while (i 100); loop ensures that the loop body runs at least once, then continues as long as i is less than or equal to 100. The if (i % 3 0) condition checks if i is divisible by 3. If true, the number is printed. The i statement increments i by 1 after each iteration.

Both loops will print the same output:

3, 6, 9, 12, 15, 18, ..., 99.

Conclusion

We have seen how to implement the same task using both while and do-while loops in Java. Each loop has its unique characteristics and can be used based on the requirement at hand. Understanding both loop structures is essential for any Java programmer.

Further Reading

For more information on Java programming, loops, and other related topics, be sure to check out the following resources:

Java While Loop from Oracle Documentation Java Do-While Loop from Oracle Documentation