In this tutorial, we will go through the square number pattern program in java. Before that, you may go through the following topic in java.
Number Square Pattern Programs in Java
The programs below take the user input for the number of rows to be displayed in the pattern. We have used a for loop to iterate.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | import java.util.Scanner; public class Main { public static void main(String args[]) { int rows, i, j; Scanner sc = new Scanner(System.in); System.out.print("Enter the no. of rows: "); rows = sc.nextInt(); for (i = 1; i <= rows; i++) { for (j = i; j <= rows; j++) System.out.print(j + " "); for (j = i - 1; j >= 1; j--) System.out.print(j + " "); System.out.println(); } } } |
Output:
Enter the no. of rows: 5
1 2 3 4 5
2 3 4 5 1
3 4 5 2 1
4 5 3 2 1
5 4 3 2 1