Write a program to take the input from the user for the row and column number. Print the no. of hourglass patterns that can be created from the given size of the matrix.

hourglass

For more java videos click
https://youtu.be/GeSDLXhzFig

import java.io.*;
class Hourglass
{
    public static void main()throws IOException
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
       System.out.println("Enter the row and column number for the matrix");
        int r=Integer.parseInt(br.readLine());
        int c=Integer.parseInt(br.readLine());
        int num=10;
        int Arr[][]=new int[r][c];
        for(int i=0;i<r;i++)
        {
            for(int j=0;j<c;j++)
            {
                Arr[i][j]=num++;
            }
        }
        System.out.println("THE MATRIX IS---------------");
        for(int i=0;i<r;i++)
        {
            for(int j=0;j<c;j++)
            {
                System.out.print(Arr[i][j]+"\t");
            }
            System.out.println();
        }
        System.out.println("_______The hour glass patterns are_______");
        for(int i=0;i<r-2;i++)
        {
            for(int j=0;j<c-2;j++)
            {
                int count=1;
                for(int k=i;k<i+3;k++)
                {
                    for(int l=j;l<j+3;l++)
                    {
                        if(count!=2)
                        {
                            System.out.print(Arr[k][l]+" ");
                        }
                        else
                        {
                            System.out.print("   "+Arr[k][l+1]);
                            break;
                        }
                    }
                    System.out.println();

                    count++;
                }
                System.out.println("------------------------------------------");
            }
        }
    }
}

Input:

Enter the row and column number for the matrix

4

5

THE MATRIX IS———————————-

10           11           12           13           14          

15           16           17           18           19          

20           21           22           23           24          

25           26           27           28           29          

_____The hour glass patterns are______
10 11 12

  16

20 21 22

——————————————

11 12 13

  17

21 22 23

——————————————

12 13 14

  18

22 23 24

——————————————

15 16 17

  21

25 26 27

——————————————

16 17 18

  22

26 27 28

——————————————

17 18 19

  23

27 28 29

——————————————

For other java related topics click https://java4school.com/data-type

LEAVE A REPLY

Please enter your comment!
Please enter your name here