0
0
Javaprogramming~5 mins

Loop execution flow in Java

Choose your learning style9 modes available
Introduction

Loops help repeat actions many times without writing the same code again and again.

When you want to print numbers from 1 to 10.
When you need to check each item in a list one by one.
When you want to keep asking a user for input until they give a valid answer.
When you want to sum all values in a collection.
When you want to repeat a task a fixed number of times.
Syntax
Java
for (initialization; condition; update) {
    // code to repeat
}

while (condition) {
    // code to repeat
}

do {
    // code to repeat
} while (condition);

The for loop repeats code while a condition is true, updating a variable each time.

The while loop repeats code as long as the condition is true, checking before each run.

Examples
This prints numbers 1 to 5, increasing i by 1 each time.
Java
for (int i = 1; i <= 5; i++) {
    System.out.println(i);
}
This does the same as the for loop but uses a while loop.
Java
int i = 1;
while (i <= 5) {
    System.out.println(i);
    i++;
}
This prints numbers 1 to 5 using a do-while loop, which runs the code at least once.
Java
int i = 1;
do {
    System.out.println(i);
    i++;
} while (i <= 5);
Sample Program

This program shows how three types of loops run and print counts from 1 to 3.

Java
public class LoopFlow {
    public static void main(String[] args) {
        System.out.println("For loop output:");
        for (int i = 1; i <= 3; i++) {
            System.out.println("Count: " + i);
        }

        System.out.println("While loop output:");
        int j = 1;
        while (j <= 3) {
            System.out.println("Count: " + j);
            j++;
        }

        System.out.println("Do-while loop output:");
        int k = 1;
        do {
            System.out.println("Count: " + k);
            k++;
        } while (k <= 3);
    }
}
OutputSuccess
Important Notes

Loops run the code inside their block repeatedly until the condition is false.

For loops are great when you know how many times to repeat.

While loops check the condition before running the code; do-while loops run the code once before checking.

Summary

Loops repeat actions to save writing the same code many times.

For, while, and do-while are common loop types with small differences in how they check conditions.

Understanding loop flow helps control how many times your code runs.