Types of loops in java with example | Loops in Java

Types of loops in java

for loop –

public class A{
	public static void main(String[] args) {
		for(int i=10; i>0; i--) {
			System.out.println(i);
		}
	}
}
Output: 
10
9
8
7
6
5
4
3
2
1

Types of loops in java

there are four types of for loop –

  1. simple for loop
  2. for each or Enhanced for Loop
  3. labeled for loop
  4. Nested for Loop

while loop

public class A  {
public static void main(String[] args) {
	int x=0;
	while(x<3) {
		System.out.println(x);
		x++;
	}
}
}
Output : 
0
1
2

do-while loop

public class A  {
public static void main(String[] args) {
	int x=100;
	do { 
		System.out.println(x);
		x++;
	}
	while(x<10);
	
}
}

Example 2

public class A{
	public static void main(String[] args) {
		int x=10;
		do {
			System.out.println(x);
			x++;
		
		
	}while (x<11);
		}
	
}
Output : 
10
11
12
13
14
public class A{
	public static void main(String[] args) {
		int x=10;
		do {
			System.out.println(x);
			x++;
		
		System.out.println(x);
	}while (x<15);
		}
	
}
Output :
10
11
11
12
12
13
13
14
14
15

You Also Learn –

Output: 100

Nested for Loop –

public class A{
	public static void main(String[] args) {
		for(int i=1; i<=3; i++) {
			for(int j=1; j<=i; j++) {
			System.out.print("*");
		}
		System.out.println();	
		}
	}
}
*
**
***
public class A{
	public static void main(String[] args) {
		int x=6;
		for(int i=1; i<=x; i++) {
			for(int j=x; j>=i; j--) {
			System.out.print("*");
		}
		System.out.println();	
		}
	}
}

Example 2

******
*****
****
***
**
*

Leave a Comment