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 –
- simple for loop
- for each or Enhanced for Loop
- labeled for loop
- 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 –
- What is Abstract Class in Java
- What is Lambda Expression in Java 8
- What is Exception Handling in Java
- Types of Exceptions in Java
- What is inheritance in Java
- What is Final Keyword in Java
- What is Interface in Java
- What is Wrapper Class in Java
- Break Keyword in Java with Example
- What is Method In Java With Example
- What is Constructor in Java With Example
- What is Polymorphism in java
- What is non-static variable in java
- Types of access specifiers in java
- What is local variable in java
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
******
*****
****
***
**
*