# Square pattern in Java

In this article, we will create a Java program displaying the square pattern. The square pattern can be implemented using loops and print statements. To make the square pattern, you can select any symbol or character you choose, such as *, #, etc.

Before implementing the square pattern, ensure you are familiar with loops in Java.

Example

Input:

`N = 6`

Output:

`* * * * * ** * * * * ** * * * * ** * * * * ** * * * * ** * * * * *`

## Using for loop

In this approach, we will display the square pattern using the nested for loop. The algorithm to display the square pattern is given below.

### Algorithm

1. Declare 3 integers variables named i, j and size.
2. Take the input for the size variable, which will define the square's number of rows and columns.
3. Create two nested for loops. Both the loops will iterate from 1 to size.
4. Print the stars for all the columns of the first row.
5. After printing the first row, print the new line after the inner for loop.

FileName: SquarePattern.java

`// Java program to display square pattern using nested for loopimport java.util.*;public class SquarePattern {    public static void main(String[] args) {        Scanner scanner = new Scanner(System.in);        int i;        int j;        System.out.print("Enter the size for rows and columns of square: ");        // take the input        int size = scanner.nextInt();        // Outer loop used for rows        for(i = 1; i <= size; i++) {            // Nested loop used for columns            for (j = 1; j<= size; j++) {                System.out.print("* ");            }            // Print the new line            System.out.println();        }    }}`

Output:

`Enter the size for rows and columns of square: 6* * * * * ** * * * * ** * * * * ** * * * * ** * * * * ** * * * * *`

## Using recursion

In this approach, we will display the square pattern using recursion

FileName: SquarePattern1.java

`// Java program to display square pattern using recursionimport java.util.*; public class SquarePattern1 {    // method to print the rows    private static void row(int i, int n) {        if(i <= n) {            column(1, n);            //Print the new line            System.out.println();            row(i+1, n);        }    }   // method to print the columns    private static void column(int j, int n) {        if (j <= n) {            System.out.print("* ");            column(j + 1, n);        }    }   // main method    public static void main(String[] args) {        Scanner scanner = new Scanner(System.in);        System.out.print("Enter the size for rows and columns of square: ");        // take the input        int size = scanner.nextInt();        int i = 1;        // function call        row(i, size);    }}`

Output:

`Enter the size for rows and columns of square: 6* * * * * ** * * * * ** * * * * ** * * * * ** * * * * ** * * * * *`