In the first part How to display pyramid patterns in Java - Part1 we have already seen how to display pyramid patterns. In this post java programs are provided for some of the other patterns.
Pattern -1
1
12
123
1234
12345
123456
12345
1234
123
12
1
For this types of patterns it is simpler to have to separate for loops. One for the increasing part and another for the decreasing part. In each of these loops there will be a nested for loop also.
import java.util.Scanner;
public class PatternsDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter highest number for the pattern (1-9) - ");
int noOfRows = sc.nextInt();
// calling method
printPattern(noOfRows);
}
private static void printPattern(int num){
for(int i = 1; i <= num; i++){
for(int j = 1; j <= i; j++){
System.out.print(j);
}
System.out.println();
}
for(int i = num; i >= 1; i--){
for(int j = 1; j < i; j++){
System.out.print(j);
}
System.out.println();
}
}
}
Pattern -2
1
22
333
4444
55555
666666
55555
4444
333
22
1
import java.util.Scanner;
public class PatternsDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter highest number for the pattern (1-9) - ");
int noOfRows = sc.nextInt();
// calling method
printPattern(noOfRows);
}
private static void printPattern(int num){
for(int i = 1; i <= num; i++){
for(int j = 1; j <= i; j++){
System.out.print(i);
}
System.out.println();
}
for(int i = num ; i >= 1; i--){
for(int j = 1; j < i; j++){
System.out.print(i -1);
}
System.out.println();
}
}
}
Pattern -3
999999999
88888888
7777777
666666
55555
4444
333
22
1
1
22
333
4444
55555
666666
7777777
88888888
999999999
import java.util.Scanner;
public class PatternsDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter highest number for the pattern (1-9) - ");
int noOfRows = sc.nextInt();
// calling method
printPattern(noOfRows);
}
private static void printPattern(int num){
for(int i = num; i >= 1; i--){
for(int j = 1; j <= i; j++){
System.out.print(i);
}
System.out.println();
}
for(int i = 1 ; i <=num ; i++){
for(int j = 1; j <= i; j++){
System.out.print(i);
}
System.out.println();
}
}
}
That's all for this topic How to display pyramid patterns in Java - Part2. If you have any doubt or any suggestions to make please drop a comment. Thanks!
Related Topics
You may also like -