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
- Declare 3 integers variables named i, j and size.
- Take the input for the size variable, which will define the square's number of rows and columns.
- Create two nested for loops. Both the loops will iterate from 1 to size.
- Print the stars for all the columns of the first row.
- 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 loop
import 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 recursion
import 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
* * * * * *
* * * * * *
* * * * * *
* * * * * *
* * * * * *
* * * * * *