The Wayback Machine - https://web.archive.org/web/20240907060356/https://www.geeksforgeeks.org/java-program-to-print-square-star-pattern/
Open In App

Java Program to Print Square Star Pattern

Last Updated : 01 Sep, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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




// Java Program to Print Square Pattern
// Case 1: Hollow rectangle
 
// Importing input output classes
import java.io.*;
 
// Main class
class GFG {
 
    // Method 1
    // To print hollow rectangle
    static void print_rectangle(int k, int l)
    {
        int a, b;
 
        // Nested for loops for iterations
 
        // Outer loop for rows
        for (a = 1; a <= k; a++) {
            // Inner loop for columns
            for (b = 1; b <= l; b++) {
                // Condition check using logical OR operator
                // over rows and columns positions
                // if found at circumference of rectangle
                if (a == 1 || a == k || b == 1 || b == l)
 
                    // Print the star pattern
                    System.out.print("*");
                else
 
                    // Rest inside square print the empty
                    // spaces
                    System.out.print(" ");
            }
 
            // By now we are done with only 1 row so
            // New line
            System.out.println();
        }
    }
 
    // Method 2
    // Main driver method
    public static void main(String args[])
    {
        // Declaring and initializing rows and columns
        // For square row = columns
 
        // Custom input initialization values
        int rows = 8, columns = 22;
 
        // Calling the method1 to print hollow rectangle
        // pattern
        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




// Java Program to Print Square Star pattern
// Case: Primary and secondary diagonal Rectangle Pattern
import java.io.*;
 
// Mai class
class GFG {
 
    // Method 1
    // To print square with primary and secondary diagonal
    static void print_squaredi(int k)
    {
        int a, b;
 
        // Nested 2 for loops for Matrix printing
 
        // Outer loop for rows
        for (a = 1; a <= k; a++) {
            // Inner loop for columns
            for (b = 1; b <= k; b++) {
                // Condition check using OR operator where
                // 1. Printing star as per first 4 checks
                // on the circumference of rectangle
                // 2. Fifth check is for diagonals
                if (a == 1 || a == k || b == 1 || b == k
                    || a == b || b == (k - a + 1))
 
                    // Print the star pattern
                    System.out.print("*");
                else
 
                    // Print the white spaces
                    System.out.print(" ");
            }
 
            // By now we are over with one row so
            // new line
            System.out.println();
        }
    }
 
    // Method 2
    // Main driver method
    public static void main(String args[])
    {
        // This time taking square so only one variable
        // needs to be declared
        // Custom input entry
        int rows = 12;
 
        // calling the method1 to print
        // square pattern with diagonal
        print_squaredi(rows);
    }
}


Output

************
**        **
* *      * *
*  *    *  *
*   *  *   *
*    **    *
*    **    *
*   *  *   *
*  *    *  *
* *      * *
**        **
************

Time complexity: O(N2) where N is given input, no of rows
Auxiliary Space : O(1)
 



Previous Article
Next Article

Similar Reads

Java Program to Print Diamond Shape Star Pattern
In this article, we are going to learn how to print diamond shape star patterns in Java. Illustration: Input: number = 7 Output: * *** ***** ******* ********* *********** ************* *********** ********* ******* ***** *** * Methods: When it comes to pattern printing we do opt for standard ways of printing them via loops only. We will try out dif
6 min read
Java Program to Print Pyramid Star Pattern
This article will guide you through the process of printing a Pyramid star pattern in Java. 1. Simple pyramid pattern Java Code import java.io.*; // Java code to demonstrate Pyramid star patterns public class GeeksForGeeks { // Function to demonstrate printing pattern public static void PyramidStar(int n) { int a, b; // outer loop to handle number
5 min read
Java Program to Print Right Triangle Star Pattern
In this article, we will learn about printing Right Triangle Star Pattern. Examples: Input : n = 5 Output: * * * * * * * * * * * * * * * Right Triangle Star Pattern: Java Code import java.io.*; // Java code to demonstrate right star triangle public class GeeksForGeeks { // Function to demonstrate printing pattern public static void StarRightTriangl
5 min read
Java Program to Print Left Triangle Star Pattern
In this article, we will learn about printing Left Triangle Star Pattern. Examples: Input : n = 5 Output: * * * * * * * * * * * * * * * Left Triangle Star Pattern: Java Code import java.io.*; // java program for left triangle public class GFG { // Function to demonstrate printing pattern public static void StarleftTriangle(int k) { int a, b; // 1st
5 min read
Java Program to Print Downward Triangle Star Pattern
Downward triangle star pattern means we want to print a triangle that is downward facing means base is upwards and by default, orientation is leftwards so the desired triangle to be printed should look like * * * * * * * * * * Example Java Code // Java Program to Print Lower Star Triangle Pattern // Main class public class GFG { // Main driver meth
2 min read
Java Program to Print Upper Star Triangle Pattern
The upper star triangle pattern means the base has to be at the bottom and there will only be one star to be printed in the first row. Here is the issue that will arise is what way we traverse be it forward or backward we can't ignore the white spaces, so we are not able to print a star in the first row using only two nested for loops. The answer t
2 min read
Java Program to Print Reverse Pyramid Star Pattern
Approach: 1. Get the number of input rows from the user using Scanner Class or BufferedReader Class object. 2. Now run two loops Outer loop to iterate through a number of rows as initialized or input is taken from reader class object in java. Now,Run an inner loop from 1 to 'i-1'Ru another inner loop from 1 to rows * 2 – (i × 2 – 1) Illustration: I
4 min read
Java Program to Print Mirror Lower Star Triangle Pattern
In this article, we are going to learn how to print mirror lower star triangle patterns in Java. Illustration: Input: number = 7 Output: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Methods: We can print mirror lower star triangle pattern using loops, so Using for loopUsing while lo
5 min read
Java Program to Print Mirror Upper Star Triangle Pattern
The pattern has two parts - both mirror reflections of each other. The base of the triangle has to be at the bottom of the imaginary mirror and the tip at the top. Illustration: Input: size = 7 Output: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Approach: Divide pattern into sub-pa
5 min read
Program to print Hut Star pattern
Given a number N such that N &gt;= 5. The task is to print a Hut Star Pattern with (N + 3) rows as shown in the below examples. Examples: Input: N = 5 Output: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Input: N = 7 Output: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
10 min read
Program to print half Diamond star pattern
Given an integer N, the task is to print half-diamond-star pattern. ************************************ Examples: Input: N = 3 Output: * ** *** ** * Input: N = 6 Output: * ** *** **** ***** ****** ***** **** *** ** * Approach: The idea is to break the pattern into two halves that is upper half and lower half. Then print them separately with the he
4 min read
Java Program to Print a Square Pattern for given integer
Write a java program to print the given Square Pattern on taking an integer as input from commandline. Examples: Input : 3 Output :1 2 3. 7 8 9 4 5 6 Input :4 Output :1 2 3 4 9 10 11 12 13 14 15 16 5 6 7 8 Java Code // Java program to print a square pattern with command // line one argument import java.util.*; import java.lang.*; public class Squar
2 min read
Java Pattern Programs - Learn How to Print Pattern in Java
In many Java interviews Star, number, and character patterns are the most asked Java Pattern Programs to check your logical and coding skills. Pattern programs in Java help you to sharpen your looping concepts(for loop). Now if you are looking for a place to get all the Java pattern exercises with solutions, then stop your search here. Here we have
15+ min read
Java Program to Print Star Pascal’s Triangle
Pascal’s triangle is a triangular array of the binomial coefficients. Write a function that takes an integer value n as input and prints the first n lines of Pascal’s triangle. Following are the first 6 rows of Pascal’s Triangle.In this article, we will look into the process of printing Pascal's triangle. Pascal’s triangle is a pattern of the trian
4 min read
Java Program to Print Alphabet Inverted Heart Pattern
Alphabet Inverted Heart Pattern consists of two parts. The upper part of the pattern is a triangle. The base of the pattern has two peaks and a gap between them. Hence, the desired pattern looks like as shown in the illustration. Illustration: A BBB CCCCC DDDDDDD EEEEEEEEE FFFFFFFFFFF GGGGGGGGGGGGG HHHHHHHHHHHHHHH IIIIIIIIIIIIIIIII JJJJJJJJJJJJJJJJ
4 min read
Java Program to Print all the Strings that Match a Given Pattern from a File
Figure a way out to print all the strings that match a given pattern from a file. To get closer to the goal, concepts of files should be crystal clear so as to think out a way to print strings later on implementing the same to reach the final goal. So prior to dealing with the strings urgency is to discuss out file concepts. Once the file concepts
5 min read
Java Program to Print Spiral Pattern of Numbers
Given a number n as the size of the matrix, the task is to print a spiral pattern of size n. Examples: Input : n = 4 Output: 1 2 3 4 12 13 14 5 11 16 15 6 10 9 8 7 Preview of the Spiral Pattern: Java Code public class GFG { public static void printSpiral(int size) { // Create row and col // to traverse rows and columns int row = 0, col = 0; int bou
3 min read
Java Program to Print Pyramid Number Pattern
Here we are getting a step ahead in printing patterns as in generic we usually play with columnar printing in the specific row keep around where elements in a row are either added up throughout or getting reduced but as we move forward we do start playing with rows which hold for outer loop in our program. Illustrations: A pyramid number pattern of
2 min read
Java Program to Print matrix in snake pattern
Given an n x n matrix .In the given matrix, you have to print the elements of the matrix in the snake pattern. Examples : Input :mat[][] = { {10, 20, 30, 40}, {15, 25, 35, 45}, {27, 29, 37, 48}, {32, 33, 39, 50}}; Output : 10 20 30 40 45 35 25 15 27 29 37 48 50 39 33 32 Input :mat[][] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; Output : 1 2 3 6 5 4 7 8 9
2 min read
Pattern pattern() method in Java with Examples
The pattern() method of the Pattern class in Java is used to get the regular expression which is compiled to create this pattern. We use a regular expression to create the pattern and this method used to get the same source expression. Syntax: public String pattern() Parameters: This method does not accepts anything as parameter. Return Value: This
2 min read
Program to print interesting pattern
Program to print following pattern: ********1******** *******2*2******* ******3*3*3****** *****4*4*4*4***** ****5*5*5*5*5**** ***6*6*6*6*6*6*** **7*7*7*7*7*7*7** Examples : Input : 4 Output : ********1******** *******2*2******* ******3*3*3****** *****4*4*4*4***** Input :5 Output : ********1******** *******2*2******* ******3*3*3****** *****4*4*4*4**
10 min read
Program to print numbers with diamond pattern
write a program where each column represents same number according to given example:Examples : Input : 5 Output : 1 212 32123 212 1 Input : 7 Output : 1 212 32123 4321234 32123 212 1 C/C++ Code // C++ program to print diamond pattern #include&lt;iostream&gt; using namespace std; void display(int n) { // sp stands for space // st stands for number i
6 min read
Program to print Inverse Diamond pattern
Given an integer n, the task is to print the Inverse Diamond Pattern in 2n-1 rows.Example: Input: n = 3 Output: *** *** ** ** * * ** ** *** *** Input: n = 7 Output: ******* ******* ****** ****** ***** ***** **** **** *** *** ** ** * * ** ** *** *** **** **** ***** ***** ****** ****** ******* ******* Approach: The full Inverse Diamond is of 2n-1 row
8 min read
Java Program to Find Area of Square Using Method Overloading
A square is a simple flat shape in a plane, defined by four points at the four corners. It has four sides with equal length and four corners with right angles. Method Overloading: Method overloading allows different methods to have the same name, but different signatures where the signature can differ by the number of input parameters or type of in
3 min read
Java Program to Add the nth Square Series
The series to work on is as follows: [Tex]1^2+2^2+3^2+4^2+...+n^2 [/Tex] Illustration Input : N = 4 Output: 30 Explanation: 12 + 22 + 32 + 42 = 1 + 4 + 9 + 16 = 30 Input: N = 5 Output: 55 Explanation: 12 + 22 + 32 + 42 + 52 = 1 + 4 + 9 + 16 + 25 = 55Approaches: Here will be provided with the value up to which sum is computed for the series. in orde
3 min read
Java program to Find the Square Root of a Number using Binary Search
Given a non-negative number find the square root of a number using the binary search approach. Examples : Input: x = 16 Output: 4 Explanation: The square root of 16 is 4. Input: x = 5 Output: 2 Explanation: The square root of 5 lies in between 2 and 3 so floor of the square root is 2. Naive Approach: Check the square of every element till n and sto
3 min read
Java Program to Generate a matrix having sum of secondary diagonal equal to a perfect square
Given an integer N, the task is to generate a matrix of dimensions N x N using positive integers from the range [1, N] such that the sum of the secondary diagonal is a perfect square. Examples: Input: N = 3Output:1 2 32 3 13 2 1Explanation:The sum of secondary diagonal = 3 + 3 + 3 = 9(= 32). Input: N = 7Output:1 2 3 4 5 6 72 3 4 5 6 7 13 4 5 6 7 1
3 min read
Java Program for Maximum and Minimum in a square matrix.
Given a square matrix of order n*n, find the maximum and minimum from the matrix given. Examples: Input : arr[][] = {5, 4, 9, 2, 0, 6, 3, 1, 8}; Output : Maximum = 9, Minimum = 0 Input : arr[][] = {-5, 3, 2, 4}; Output : Maximum = 4, Minimum = -5 Naive Method : We find maximum and minimum of matrix separately using linear search. Number of comparis
3 min read
Java Program for Maximum size square sub-matrix with all 1s
Write a Java program for a given binary matrix, the task is to find out the maximum size square sub-matrix with all 1s. Recommended: Please solve it on "PRACTICE" first, before moving on to the solution.Approach: Let the given binary matrix be M[R][C]. The idea of the algorithm is to construct an auxiliary size matrix S[][] in which each entry S[i]
5 min read
Java Program to Inplace rotate square matrix by 90 degrees | Set 1
Given a square matrix, turn it by 90 degrees in anti-clockwise direction without using any extra space.Examples : Input: Matrix: 1 2 3 4 5 6 7 8 9 Output: 3 6 9 2 5 8 1 4 7 The given matrix is rotated by 90 degree in anti-clockwise direction. Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Output: 4 8 12 16 3 7 11 15 2 6 10 14 1 5 9 13 The given matr
5 min read
Article Tags :
Practice Tags :