Design and implement a Java program for programming exercise 5.18, page 194, fro
ID: 3674386 • Letter: D
Question
Design and implement a Java program for programming exercise 5.18, page 194, from the textbook (name it Patterns). Document your code, and organize and space the outputs. Divide your code into 4 sections, one for each pattern. Notice that your program will print the patterns one after the other, not next to each other as shown in the textbook. Use escape characters and formatting objects when applicable.
5.18: (Display four patterns using loops) Use nested loops that display the following patterns in four separate programs:
Pattern A
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
Pattern B
1 2 3 4 5 6
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
Pattern C
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
Pattern D
1 2 3 4 5 6
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
Explanation / Answer
Please find the required solution:
public class Print4Patterns {
public static void main(String[] args) {
System.out.println("Pattern A");
for (int i = 1; i <= 6; i++) {
for (int j = 1; j < i + 1; j++) {
System.out.print(j);
}
System.out.println();
}
System.out.println("Pattern B");
for (int i = 6; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
System.out.print(j);
}
System.out.println();
}
System.out.println("Pattern C");
for (int i = 1; i <= 6; i++) {
for (int j = 1; j < i + 1; j++) {
System.out.print(j);
}
System.out.println();
}
System.out.println("Pattern D");
for (int i = 6; i >= 1; i--) {
for (int k = 0; k < 6 - i ; k++) {
System.out.print(" ");
}
for (int j = 1; j <= i; j++) {
System.out.print(j);
}
System.out.println();
}
}
}
Sample output:
Pattern A1
12
123
1234
12345
123456
Pattern B
123456
12345
1234
123
12
1
Pattern C
1
12
123
1234
12345
123456
Pattern D
123456
12345
1234
123
12
1
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.