Skip to content
Advertisement

Print a Z shape pyramid using * stars

I am trying to write a program that outputs a Z pattern that is n number of * across the top, bottom, and connecting line using for loops.

Example:

JavaScript

This is my current code, it’s producing a half pyramid upside down.

JavaScript

Advertisement

Answer

This is the logic in the following code:

  • Loop over each row of the output (so from 0 to n excluded so that we have n rows)
  • Loop over each column of the output (so from 0 to n excluded so that we have n columns)
  • We need to print a * only when it is the first row (x == 0) or the last row (x == n - 1) or the column is in the opposite diagonal (column == n - 1 - row)

Code:

JavaScript

Sample output for n = 6:

JavaScript

(Note that this output has trailing white-spaces for each row, you did not specify whether they should be included, but it is easy to remove them by adding another check).

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement