How to print a square with diagonal pattern.

Square with Diagonal  Pattern

In Square pattern it is shown with 2 vertical and 2 horizontal line,Diagonal is shown with  cross line.
Coding for pattern-:

package pattern;
import java.util.Scanner;
public class diagonal_square {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print(“Enter number=”);
int n = s.nextInt();
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
if (i == 1 || i == n)
{
System.out.print(“* “);
}
else
if (j == 1 || j == n)
{
System.out.print(“* “);
}
else
if(i==j||i==((n-j)+1))
System.out.print(“* “);
else
{
System.out.print(” “);
}
}
System.out.println(“”);
}
}
}

Output-:

1 thought on “How to print a square with diagonal pattern.”

  1. This is a much simpler solution.

    for(i=1;i<=n;i++)
    {
    for(j=1;j<=n;j++)
    {
    if(i==1 || i==n||j==1||j==n||i==j||j==(n-i+1))
    System.out.print("$");
    else
    System.out.print(" ");
    }System.out.println();
    }

Leave a Reply