Open In App

Java For Loop

Last Updated : 15 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Java for loop is a control flow statement that allows code to be executed repeatedly based on a given condition. The for loop in Java provides an efficient way to iterate over a range of values, execute code multiple times, or traverse arrays and collections.

Example:

class Geeks {
  
    public static void main(String args[]) {
      
        // for loop to print numbers from 1 to 5
        for (int i = 1; i <= 5; i++) {
          
            System.out.println("" + i);
        }
        
        System.out.println("Loop has ended.");
    }
}

Output
1
2
3
4
5
Loop has ended.

Dry-Running Above Example

  1. The program starts.
  2. The for loop initializes i to 1.
  3. Condition i <= 5 is checked.
    • If true:
      • Statement inside the loop executes, printing the current value of i.
      • Increment i by 1.
    • If false:
      • Loop terminates, and the program continues.
  4. Steps repeat until i becomes 6, at which point the condition fails, and “Loop has ended.” is printed.
For Loop in Java

Syntax

for (initialization expr; test expr; update exp)
{
// body of the loop
// statements we want to execute
}

Working

  1. Control enters the for loop.
  2. Initialization is executed once at the beginning of the loop.
  3. The Condition is evaluated:
    1. If true, the control moves to Step 4.
    2. If false, the control jumps to Step 7.
  4. The body of the loop is executed.
  5. Control moves to the Updation step.
  6. After Updation, the flow returns to the Condition (Step 3) and repeats the process.
  7. Once the condition becomes false, the control exits the for loop, and statements outside the loop are executed.

Java for loop is divided into various parts as mentioned below:

  1. Initialization Expression
  2. Test Expression
  3. Update Expression

1. Initialization Expression

Initializes the loop variable. This is executed once at the start of the loop.

Example:  

int i = 1;

2. Test Expression

Tests the loop condition. If true, the loop body is executed; otherwise, the loop terminates.

Example:  

i <= 10

3. Update Expression

After executing the loop body, this expression increments/decrements the loop variable by some value. 

Example:  

i++;

Flow Chart

Flow chart for loop in Java


Example 1: Printing Numbers from 1 to 10

// Java program to print numbers from 1 to 10
class GFG {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            System.out.println(i);
        }
    }
}

Output
1
2
3
4
5
6
7
8
9
10

Example 2: Printing “Hello World” 5 Times  

// Java program to illustrate for loop
class GFG {
    public static void main(String args[]) {
      
        // Writing a for loop
        // to print Hello World 5 times
        for (int i = 1; i <= 5; i++)
            System.out.println("Hello World");
    }
}

Output
Hello World
Hello World
Hello World
Hello World
Hello World

Example 3: Calculating Sum from 1 to 20

// Java program to calculate the 
// sum of numbers from 1 to 20
class GFG {
    public static void main(String args[]) {
        int s = 0;

        // for loop begins
        // and runs till x <= 20
        for (int x = 1; x <= 20; x++) {
            s = s + x;
        }
        System.out.println("Sum: " + s);
    }
}

Output
Sum: 210

Nested For Loop

Java Nested For Loop is a concept of using a for loop inside another for loop. It is commonly used for multidimensional problems.

Example: Printing a Matrix-like Pattern

// Java program to illustrate 
// Nested For Loop
class GFG {
  
    public static void main(String[] args) {
      
        for (int i = 1; i <= 3; i++) {
          
            for (int j = 1; j <= 3; j++) {
              
                System.out.print("(" + i + "," + j + ") ");
            }
            System.out.println();
        }
    }
}

Output
(1,1) (1,2) (1,3) 
(2,1) (2,2) (2,3) 
(3,1) (3,2) (3,3) 

Note: To know more about Nested loops refer Nested loops in Java.

Java Infinite for Loop

An infinite loop occurs when the loop’s condition never becomes false. In the example below, the condition i >= 1 always evaluates to true, leading to an infinite loop.

Example 1:

// Java Program to Illustrate 
// infinite loop
class GFG {
    public static void main(String args[])
    {
        for (int i = 1; i >= 1; i++) {
            System.out.println("Infinite Loop " + i);
        }
    }
}

Output:

Infinite Loop 1
Infinite Loop 2
...

Example 2: Another way to create an infinite loop is by using empty semicolons ;; in the for loop.

public class GFG {
    public static void main(String[] args) {
      
        for (;;) {
            System.out.println("Infinite Loop");
        }
    }
}

Output:

infinitive loop
infinitive loop
....

Important Note: A “Time Limit Exceeded” error occurs when a program runs longer than the time allocated for execution, due to infinite loops.

Advantages of for Loop

  • This is ideal for iterating over a known range or collection.
  • Efficient syntax for initialization, condition checking, and incrementing.
  • Easy to control the number of iterations.
  • Efficient for looping through arrays and collections.


Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg