Looping or Iteration Statements

for loop

Syntax :
for(<initialization><condition><increment>)
{
	Statement 1;
	Statement 2;
	Statement n;
}
                    
Tips
  • If you ignore the braces after loop statement the first statement after loop is executed in loop.
  • If you put ; (semi colon) to loop without braces no statement is executed.
  • If you put ; (semi colon) to loop with braces the body of the loop is executed once.
/*
    for loop Example
    Save with file name ForLoop.java
*/

public class ForLoop
{
	public static void main(String args[])
	{
		System.out.println();
		System.out.println("for loop Example ");
		System.out.println("================");
		System.out.println();

		for(int count=1 ; count<=10 ; count++)
		{
			// POST INCREMENT
			System.out.println("Loop Statement : " + count);
		}

		System.out.println();
		System.out.println("Loop 2 output");
		System.out.println();
		// ANOTHER WAY
		int i = 0;
		for(;i<10;)
		{
			// PRE INCREMENT WITH IN THE BODY OF THE LOOP
			System.out.println("Loop Statement : " + ++i);
		}
		System.out.println();
		System.out.println("Loop 3 output");
		System.out.println();
		// LOOP WITH NO BODY 
		int j=0;
		for(;j<10;j++); // ; (SEMICOLON) IGNORE THE BODY OF THE LOOP
		{
			System.out.println("loop body ignore");
		}
		System.out.println("j value after loop execution : " + j);

	}
}
                        

while loop

Syntax :
while(<condition>)
{
	Statement 1;
	Statement 2;
	Statement n;
}
                    
/*
    while loop Example
    Save with file name WhileLoop.java
*/

public class WhileLoop
{
	public static void main(String args[])
	{
		System.out.println();
		System.out.println("while loop Example ");
		System.out.println("==================");
		System.out.println();

		int count = 1;
		while(count<=10)
		{
			// POST INCREMENT
			System.out.println("Loop Statement : " + count);
			count++;
		}
	}
}
                        

do while loop

The statements within the do while loop are executed at least once. So the do while loop is called bottom tested loop.

Syntax :
do
{
	Statement 1;
	Statement 2;
	Statement n;
} while(<condition>);
                    
/*
    do while loop Example
    Save with file name DoWhileLoop.java
*/

public class DoWhileLoop
{
	public static void main(String args[])
	{
		System.out.println();
		System.out.println("do while loop Example ");
		System.out.println("=====================");
		System.out.println();

		int count = 1;
		do
		{
			//POST INCREMENT
			System.out.println("Loop Statement : " + count);
			count++;
		} while(count<=10);
	}
}