Here, we will implement a Java program to print the square star pattern. We will print the square star pattern with diagonals and without diagonals.
Example:
**********************
* *
* *
* *
* *
* *
* *
**********************
Approach:
Step 1: Input number of rows and columns.
Step 2: For rows of rectangle run the outer loop from 1 to rows.
for (i = 1; i < = rows; i++)
Step 3: For the column of the rectangle run the inner loop from 1 to columns.
for (j = 1; j < = columns; j++)
Step 4: Print star for first or last row or for first or last column, otherwise print blank space.
Step 5: After printing all columns of a row, print the newline after the inner loop.
Example 1: Star square pattern without diagonals
Java
import java.io.*;
class GFG {
static void print_rectangle( int k, int l)
{
int a, b;
for (a = 1 ; a <= k; a++) {
for (b = 1 ; b <= l; b++) {
if (a == 1 || a == k || b == 1 || b == l)
System.out.print( "*" );
else
System.out.print( " " );
}
System.out.println();
}
}
public static void main(String args[])
{
int rows = 8 , columns = 22 ;
print_rectangle(rows, columns);
}
}
|
Output
**********************
* *
* *
* *
* *
* *
* *
**********************
Time complexity: O(R*C) for given no of rows R and columns C
Auxiliary space: O(1) because it is using constant space
Now taking it a step further as in above we simply inserted empty spaces inside the rectangle. In mathematics, we already have come across diagonals, so we can print them too in the above case.
Example 2: Star square pattern with diagonals
Java
import java.io.*;
class GFG {
static void print_squaredi( int k)
{
int a, b;
for (a = 1 ; a <= k; a++) {
for (b = 1 ; b <= k; b++) {
if (a == 1 || a == k || b == 1 || b == k
|| a == b || b == (k - a + 1 ))
System.out.print( "*" );
else
System.out.print( " " );
}
System.out.println();
}
}
public static void main(String args[])
{
int rows = 12 ;
print_squaredi(rows);
}
}
|
Output
************
** **
* * * *
* * * *
* * * *
* ** *
* ** *
* * * *
* * * *
* * * *
** **
************
Time complexity: O(N2) where N is given input, no of rows
Auxiliary Space : O(1)
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
01 Sep, 2022
Like Article
Save Article