For loop

Loop constructs are used to iterate a piece of code again and again until specified condition is true. for example if want to print "hello world" message 10 times, without loop constructs we have to write printing statemnt 10 times. In order to simplifying the iteration process, loop constructs are introduced. Loop in java are same as in c or c++. In java we have while, do-while, for and for each.


Syntax of for loop

    
for(intialisation ; condition ; increament or decrement )
{
statement1;
statement2;
..........
..........
statementn;
}

For loop used because of its simplicity. In for loop three parts are there, first is initialisation. Second is condition checking and third is increment or decrement.



In while loop condition has to be specified, otherwise compiler will generate an error.


Example :


// file: forloop.java 
// www.jgyan.com
class forloop
{
public static void main(String ...arg)
{
int i;
for(i=2;i<=100;i=i+2)
{
System.out.println(i);
}
}
}


It is not necessary to initialise variable in for loop or increment value in for loop. It can be done outside as well. Same program can be written without initialization and increment.


Example :


//file: forloop1.java 
//www.jgyan.com
class forloop1
{
public static void main(String ...arg)
{
int i=2;
for( ;i<=100;)
{
System.out.println(i);
i=i+2;
}
}
}

In above program only condition is specified in for loop. Can we skip condition also?. Yes we can in that case by default for loop consider that true. For loop without condition will run forever(infinite loop).


Syntax :

  for( ; ; ) // infinite loop 
{
}

Important ! In for loop two semi colon';' are must.