For Loop

For loop is the same as the while loop. It is used to repeat a block of code again and again. But the syntax of the for loop is different quite different from the while loop.

Syntax

for(initializationState; conditionState; updationState) {
            //block of code here
        }

As you can see, unlike a while loop, for loop, have 2 additional states which are the initialization state, and the updation state. While loop also had these states but we were writing them in between the code.

Example :

// WHILE LOOP EXAMPLE 
public class PrintHelloWorld100Times {
    public static void main(String[] args) {
        int count = 1; // Initalization State
        while(count<=100) // Condition State 
         {
            System.out.println(count+". Hello World");
            count++; // Updation State
        }
    }
}

We will write a program to run "Hello world" ten times in for loop.

Example 1 :

Write a Program to print Hello World 10 Times.

public class ForLoop {
    public static void main(String[] args) {
        for(int num = 1; num <= 10; num++) {
            System.out.println(num+". Hello World");
        }
    }
}

Example 2 :

Print a Square Pattern.

public class SquarePattern {
    public static void main(String[] args) {
        for(int i = 0; i<4;i++) {
            System.out.println("* * * *");
        }
    }
}

Example 3 :

Print the Reverse of a number.

public class ReverseOfNumber {
    public static void main(String[] args) {
        int num = 2121635200,rem=0;
        while(num > 0) {
            rem = num%10;
            System.out.print(rem);
            num /= 10;
        }
    }
}

Example 3 :

Print the number in reverse.

public class ReverseOfNumber {
    public static void main(String[] args) {
        int num = 210,rem=0;
        while(num > 0) {            
            rem = (rem*10)+(num%10); 
            num /= 10;            
        }
        System.out.println(rem);
    }    
}

So, This is the end of for loops in Java.

I hope you liked it.