Krivalar Tutorials 
Krivalar Tutorials

Java for loop in programming


<<Previous

Next >>





for statement

for loop is used to execute a block of statements repetitively. You can execute the number of the times you want to. You can specify an exit criteria for the loop. for loop has initialization expression, exit condition expression and step-wise progress expression

for statement - Syntax

for(initialization statement;
		termination statement that returns true or false;
		loop counter){
	statement;
}

for statement - Example


public class ForLoop {
public static void main(String a[]){
	for(int i=0; i<10;i++)
	{
		System.out.print("" + i + ",");
	}
}
}




The above for loop prints

0,1,2,3,4,5,6,7,8,9,

In the above for loop:

int i=0 - is the initialization statment
i<10 - is the termination statement based on which the block executes if the condition returns true
i++ - is the loop counter and it is an expression that can be used to modify the values in the termination statement.

This statement can be increment or decrement or any other evaluation.

  • the initialization statement in the for loop executes once and only once at the start of the for loop
  • termination statement is executed each and every time, the block is executed and the block executes only when the condition in the termination statement is true.
  • loop counter is executed each and every time after the termination statement in for loop

for loop can work without initialization statement

public class ForLoopNoInitialization {
public static void main(String a[]){
	int i=0;
	for(;i<10;i++)	{
		System.out.print(
			"" + i + ",");
	}
}
}
Above code will print:
0,1,2,3,4,5,6,7,8,9,

for loop can work without termination statement, in which case, you have to take care of terminating the loop using break statement or any other way.


public class ForLoopNoTermination {
public static void main(String a[]){
	int i=0;
	for(;;i++){
		System.out.print("" + i + ",");
		if(i>=10){ break; }

	}
}
}
Above code will print:
0,1,2,3,4,5,6,7,8,9,
for loop can work without loop counter statement in which case you need to find a way to run the loop for different values.

public class ForLoopNoInitNoConditionNoTermination {
public static void main(String a[]){
	int i=0;
	for(;;){
		if(i>=10){
			break;
		}
		System.out.print("" + i + ",");
		i++;
	}
}
}
This will print:
0,1,2,3,4,5,6,7,8,9,


<<Previous

Next >>





















Searching using Binary Search Tree