dsa

Java for Loop

In this tutorial, we will learn how to use for loop in Java with the help of examples and we will also learn about the working of Loop in computer programming.

  • Introduction

    The Java for loop is a control flow statement that iterates a part of the programs multiple times.

  • When to use :

    If the number of iteration is fixed, it is recommended to use for loop.

  • Syntax :

    
    for( init ; condition ; incr/decr )
    {  
    	// code to be executed 
    }
  • Working

    Flow Chart
    Flow chart for for-loop

  • Example :

    
    //for loop  
    for(int i=1 ; i<=5 ; i++)
    {  
    	System.out.println("Thanks for using CODEMISTIC!");  
    }  

    Output :

    
    Thanks for using CODEMISTIC!
    Thanks for using CODEMISTIC!
    Thanks for using CODEMISTIC!
    Thanks for using CODEMISTIC!
    Thanks for using CODEMISTIC!

    Explanation :
    In the above example, we have :

    • initialization expression: int i = 1
    • test expression: i <=5
    • update expression: ++i

    Here, initially, the value of i is 1. So the test expression evaluates to true for the first time. Hence, the print statement is executed. Now the update expression is evaluated.

    Each time the update expression is evaluated, the value of i is increased by 1. Again, the test expression is evaluated. And, the same process is repeated.

    This process goes on until i is 6. When i is 6, the test expression (i <= 5) is false and the for loop terminates.

Infinite Loop

One of the most common mistakes while implementing any sort of looping is that that it may not ever exit, that is the loop runs for infinite time. This happens when the condition fails for some reason.

  • Syntax for infinite loop :

     
    for( ; ; )
    {  
    	 // code to be executed
    }  
  • Example for showing various pitfalls :

     
    //Java program to illustrate various pitfalls. 
    public class LooppitfallsDemo 
    { 
        public static void main(String[] args) 
        { 
            // infinite loop because condition is not apt 
            // condition should have been i>0. 
            for (int i = 5; i != 0; i -= 2) 
            { 
                System.out.println(i); 
            }
        } 
    }