15.0k views
5 votes
Write a program that uses nested loop or for statements to display Pattern A below, followed by an empty line and then another set of loops that displays Pattern B. Once again no setw implementation is allowed here but you must use nested loop or for statements with proper indentation to generate these patterns. Use meaningful variable identifier names, good prompting messages and appropriate comments for each loop segment as well as other sections in the body of your program.

Note: Each triangle has exactly seven rows and the width of each row is an odd number. The triangles have appropriate labels displayed.


Pattern A

+

+++

+++++

+++++++

+++++++++

+++++++++++

+++++++++++++

Pattern B

+++++++++++++

+++++++++++

+++++++++

+++++++

+++++

+++

+

User Sacapeao
by
5.3k points

1 Answer

2 votes

Answer:

public class Pyramid {

public static void main(String[] args) {

int h = 7;

System.out.println("Pattern A");

for(int i = 1; i <= h; ++i)

{

for(int j = 1; j <= i; ++j) {

System.out.print("+");

}

System.out.println();

}

System.out.println();

System.out.println("Pattern B");

for (int i = 1; i<=h; ++i)

{

for(int j = h; j >=i; --j){

System.out.print("+");

}

System.out.println();

}

}

}

Step-by-step explanation:

  • The trick in this code is using a nested for loop
  • The outer for loop runs from i = 0 to the heigth of the triangle (in this case 7)
  • The inner for loop which prints the (+) sign runs from j = 0 to j<=i
  • It prints the + using the print() function and not println()
  • In the pattern B the loop is reversed to start from i = height
User Adedoy
by
5.9k points