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
// Java program to print a square pattern with command // line one argument import java.util.*; import java.lang.*; Â
public class SquarePattern { Â Â Â Â public static void main(String[] args) Â Â Â Â { Â Â Â Â Â Â Â Â Scanner sc = new Scanner(System.in); Â Â Â Â Â Â Â Â System.out.println("Enter a number"); Â Â Â Â Â Â Â Â int number = sc.nextInt(); Â Â Â Â Â Â Â Â int arr[][] = PrintSquarePattern(number); Â
        // int num = 3;         int k = 0, m = number - 1, n = number;         int l = 0;         if (number % 2 == 0)             m = number - 1;         else            m = number; Â
        for (int i = 0; i < n / 2; i++) {             for (int j = 0; j < n; j++) {                 System.out.format("%3d", arr[k][j]);             }             System.out.println("");             l = l + 2;             k = l;             // System.out.println("");         }         k = number - 1;         for (int i = n / 2; i < n; i++) {             for (int j = 0; j < n; j++) {                 System.out.format("%3d", arr[k][j]);             }             m = m - 2;             k = m;             System.out.println("");         }     } Â
    public static int[][] PrintSquarePattern(int n)     {         int arr[][] = new int[n][n];         int k = 1;         for (int i = 0; i < n; i++) {             for (int j = 0; j < n; j++) {                 arr[i][j] = k;                 k++;             }         }         return arr;     } } |
Input :
5
Output :
Enter a number 1 2 3 4 5 11 12 13 14 15 21 22 23 24 25 16 17 18 19 20 6 7 8 9 10
Time complexity: O(n^2) for given input n
Auxiliary Space: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!
