Loops In Java


there are three kinds of loops

1.  for loop

for(initialization , condition , iteration){

}

 

In case of for loop, you can set a starting value, set a condition  and then you execute it.

For loop checks the condition of the loop in the beginning of execution.

2.  while loop

while(condition){

}

 

In while loop, you can set a condition and loop will continue to endlessly execute until condition holds true.

While loop checks the condition before the loop execution

 

3.  do while loop

do{

} while(condition);

Do while loop executes just like normal while loop, except that it checks the condition after the execution of loop.


eg:



myClass.java:

package iteration_case;

public class myClass {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		int i=0;
		
		// using for loop
		System.out.println("for loop execution");
		for(i=0;i<10;i++) {
			System.out.println("i = "+i);
		}
		
		// Using while loop
		System.out.println("while loop execution");
		i=0;
		while(i<10) {
			System.out.println("i = "+i);
			i++;
		}
		
		// Using do while loop
				System.out.println("do while loop execution");
				i=0;
				do{
					System.out.println("i = "+i);
					i++;
				}while(i<10); 

	}

}
output:
for loop execution
i = 0
i = 1
i = 2
i = 3
i = 4
i = 5
i = 6
i = 7
i = 8
i = 9
while loop execution
i = 0
i = 1
i = 2
i = 3
i = 4
i = 5
i = 6
i = 7
i = 8
i = 9
do while loop execution
i = 0
i = 1
i = 2
i = 3
i = 4
i = 5
i = 6
i = 7
i = 8
i = 9



Related Tutorials