Home > Java > javaTutorial > Java program to print a square pattern of a given integer

Java program to print a square pattern of a given integer

WBOY
Release: 2023-08-20 11:21:24
forward
1226 people have browsed it

Java program to print a square pattern of a given integer

Print the square pattern of a 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;
   }
}
Copy after login

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
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template