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 25 26 27 28 29 | import java.util.Scanner; public class Main { public static void main(String args[]) { int rows, i, j, k; Scanner sc = new Scanner(System.in); System.out.print("Enter the no. of rows: "); rows = sc.nextInt(); for (i = 1; i <= rows; i++) { j = (i *2) - 1; for (k = i; k <= rows; k++) { System.out.print(j + " "); j += 2; } for (j = (i *2) - 3; j >= 1; j -= 2) System.out.print(j + " "); System.out.println(); } } } |
Output:
Enter the no. of rows: 5
1 3 5 7 9
3 5 7 9 1
5 7 9 3 1
7 9 5 3 1
9 7 5 3 1