Nested loops consist of an outer loop and one or more inner loops. Each time the outer loop is repeated, the inner loops are reentered and started anew.
Try this simple program.
public class Pattern {
public static void main (String[] args) {
for (int i=0; i<3; i++){ //outer loop
System.out.println("loop i = " +i);
for (int j=0; j<5; j++){ //inner loop
System.out.println("#loop j = " + j);
}
System.out.println();
}
}
}
You will get an output like this:
loop i = 1
#loop j = 0
#loop j = 1
#loop j = 2
#loop j = 3
#loop j = 4
loop i = 2
#loop j = 0
#loop j = 1
#loop j = 2
#loop j = 3
#loop j = 4
loop i is the outer loop and loop j is the inner loop.
Each time the outer loop is repeated, the inner loops are reentered and started anew. The inner loop must complete before start a new loop for outer loop.
public class Pattern1 {
public static void main (String[] args) {
for (int i=0; i<3; i++){
for (int j=0; j<5; j++){
System.out.print(j);
}
System.out.println();
}
}
}
The output will be:
01234
01234
01234
import java.util.Scanner;
public class Pattern2 {
public static void main (String[] args) {
for (int i=0; i<3; i++){
for (int j=0; j<5; j++){ // inner loop
System.out.print(i); // print i
}
System.out.println();
}
}
}
In this program, instead of it print j in inner loop, it print i. The output will be:
00000
11111
22222
import java.util.Scanner;
public class Pattern1 {
public static void main (String[] args) {
for (int i=1; i<=5; i++){
for (int j=1; j<=i; j++){
System.out.print(j+" ");
}
System.out.println();
}
}
}
The output will be:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Use nested loops that print the following patterns in four separate programs.
Pattern 4
1 2 3 4 5 6
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
Pattern 5
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
6 5 4 3 2 1
Pattern 6
6 5 4 3 2 1
5 4 3 2 1
4 3 2 1
3 2 1
2 1
1