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:
Enter a number: 6 ****** * * * * ******
This is my current code, it’s producing a half pyramid upside down.
import java.util.*; public class ZShape { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a number: "); int n = input.nextInt(); for (int x = 0; x <= n; x++) { for (int y = n; y >= 1; y--) { if (y > x) { System.out.print("* "); } else System.out.print(" "); } System.out.println(); } } }
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 haven
rows) - Loop over each column of the output (so from 0 to
n
excluded so that we haven
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:
public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a number: "); int n = input.nextInt(); for (int row = 0; row < n; row++) { for (int column = 0; column < n; column++) { if (row == 0 || row == n - 1 || column == n - 1 - row) { System.out.print("*"); } else { System.out.print(" "); } } System.out.println(); } }
Sample output for n = 6
:
****** * * * * ******
(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).