0
0
Javaprogramming~5 mins

For loop syntax in Java

Choose your learning style9 modes available
Introduction

A for loop helps you repeat a set of actions many times without writing the same code again and again.

When you want to count from 1 to 10 and do something each time.
When you need to go through all items in a list or array one by one.
When you want to repeat a task a fixed number of times, like printing a message 5 times.
When you want to process each character in a word or sentence.
When you want to sum numbers from 1 to 100 automatically.
Syntax
Java
for (initialization; condition; update) {
    // code to repeat
}

initialization sets a starting point, like int i = 0;.

condition is checked before each loop; if true, the loop runs.

update changes the loop variable, usually increasing or decreasing it.

Examples
This prints numbers 0 to 4, counting up by 1 each time.
Java
for (int i = 0; i < 5; i++) {
    System.out.println(i);
}
This counts down from 10 to 1, printing each number.
Java
for (int i = 10; i > 0; i--) {
    System.out.println(i);
}
This prints even numbers from 0 to 8 by adding 2 each time.
Java
for (int i = 0; i < 10; i += 2) {
    System.out.println(i);
}
Sample Program

This program counts from 1 to 5 and prints each number with the word "Count:" before it.

Java
public class ForLoopExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            System.out.println("Count: " + i);
        }
    }
}
OutputSuccess
Important Notes

The loop variable (like i) is usually declared inside the for loop.

If the condition is false at the start, the loop code will not run at all.

You can use any variable name, but i, j, and k are common for loops.

Summary

A for loop repeats code a set number of times.

It has three parts: start, condition to keep going, and how to change the counter.

Use it when you know how many times you want to repeat something.