Sunday, 3 April 2016

for Loop Variations in Java

Variations of for loop in Java


               In order to increase the applicability of the for loop, it supports number of variations. for loop can be used without initialization statement, condition statement and iteration statement. They can kept empty.

for loop Variations

Variation 1: No initialization and iteration statement


               In the below program, we have intentionally kept the initialization and iteration part empty. Here we initialized the variable before the for loop and kept the increment statement inside the for loop. 

Program:


public class ForLoopVariationType1
{
    public static void main(String[] args)
    {
        int i=8;
        for(;i<12 i="">
        {
            System.out.println("i="+i);
            i++;
        }        
    }
}

Output:


i=8
i=9
i=10
i=11

Variation 2: No Condition Statement


               Here, we use the condition and exit statement inside the for loop. This is done by using the break statement inside the for loop body. when the value of i becomes 10 , the break statement terminates the for loop.


Program:


public class ForLoopVariationType2
{
    public static void main(String[] args)
    {
        int i=8;
        for(;;)
        {
            System.out.println("i="+i);
            i++;
            if (i==10)
                break;
        }      
    }
}

Output:


i=8
i=9
i=10
i=11

Variation 3: Infinite Loop


               Here is one more for loop variation. You can intentionally create an infinite loop (a loop that never terminates) if you leave all three parts of the for empty.

Program:


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

Output:


Infinite Loop
Infinite Loop
Infinite Loop
Infinite Loop
Infinite Loop
Infinite Loop
Infinite Loop


Note: The same Infinite Loop Message Continues as it is an infinite condition-less loop.

2 comments :

  1. There is definately a great deal to know about this subject. I like all of the points you've made. 温哥华辅导

    ReplyDelete