Computer >> Computer tutorials >  >> Programming >> Java

Java Program to Print a Square Pattern for given integer


To print a square pattern for given integer, the Java code is as follows −

Example

import java.util.*;
import java.lang.*;
public class Demo{
   public static void main(String[] args){
      Scanner my_scan = new Scanner(System.in);
      System.out.println("Enter a range");
      int my_num = my_scan.nextInt();
      int my_arr[][] = print_pattern(my_num);
      int eq_val = 0, sub_val = my_num - 1, n = my_num;
      int l = 0;
      if (my_num % 2 == 0)
         sub_val = my_num - 1;
      else
         sub_val = my_num;
      for (int i = 0; i < n / 2; i++){
         for (int j = 0; j < n; j++){
            System.out.format("%3d", my_arr[eq_val][j]);
         }
         System.out.println("");
         l = l + 2;
         eq_val = l;
      }
      eq_val = my_num - 1;
      for (int i = n / 2; i < n; i++){
         for (int j = 0; j < n; j++){
            System.out.format("%3d", my_arr[eq_val][j]);
         }
         sub_val = sub_val - 2;
         eq_val = sub_val;
         System.out.println("");
      }
   }
   public static int[][] print_pattern(int n){
      int my_arr[][] = new int[n][n];
      int eq_val = 1;
      for (int i = 0; i < n; i++){
         for (int j = 0; j < n; j++){
            my_arr[i][j] = eq_val;
            eq_val++;
         }
      }
      return my_arr;
   }
}

Output

Enter a range
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

A class named Demo contains the main function. A Scanner instance is created to take the upper limit range. Every integer upto that range is iterated and pattern is printed by calling the ‘print_pattern’ function.

The ‘print_pattern´ function is defined after the main function. It takes the upper range as parameter, and creates a two dimensional array and iterates through it, and defines a value as 1 beforehand, which is incremented after every iteration of the array. The array is returned as output from the function.