Print the square pattern of a given integer, the Java code is as follows −
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; } }
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 file named Demo The class contains the main function. Created a Scanner instance to obtain the upper range. Iterate over each integer in the range and print out the pattern by calling the 'print_pattern' function.
The 'print_pattern' function is defined after the main function. It takes an upper range as a parameter and creates a 2D array and iterates over it, previously defining a value as 1 which increments each time the array is iterated over. This array is returned as the output of the function.
The above is the detailed content of Java program to print a square pattern of a given integer. For more information, please follow other related articles on the PHP Chinese website!