# Java Program to Find Number of Rectangles in N*M Grid

In this article we will discuss about how to find Number of Rectangles in N*M Grid using Java programming language.

## Java Program to Find Number of Rectangles in N*M Grid

Before jumping into the program directly, let’s first know how can we find the number of rectangles in M*N grid.

Formula to Find Total Rectangles in M*N Grid: (M(M+1)(N)(N+1))/4
Example:

When M=2 and N=2

Number rectangles: (M(M+1)(N)(N+1))/4

=> (2(2+1)(2)(2+1))/4=(2*3*2*3)/4

=> 36/4 = 9

Let’s see different ways to find number of Rectangles in N*M Grid.

### Method-1: Java Program to Find Number of Rectangles in N*M Grid By Using Static Value

Approach:

1. Declare the value for ‘m‘ and ‘n‘.
2. Then call the rectangleCount() method by passing m and n value as parameter.
3. In this method the number of rectangle possible will be calculated using the formula  (M(M+1)(N)(N+1))/4
4. Then print the result.

Program:

// JAVA Code to count number of
// rectangles in N*M grid

public class Main
{
// Driver method
public static void main(String[] args)
{
//Value of 'n' and 'm' are declared
int n = 2, m = 2;
//calling the rectangleCount() user defined method
System.out.println("Number of rectangle : "+rectangleCount(n, m));
}

//rectangleCount() method to find the number of rectangles
public static long  rectangleCount(int n, int m)
{
return (m * n * (n + 1) * (m + 1)) / 4;
}
}

Output:

Number of rectangle : 9

### Method-2: Java Program to Find Number of Rectangles in N*M Grid By User Input Value

Approach:

1. Take user input the value for ‘m‘ and ‘n‘.
2. Then call the rectangleCount() method by passing m and n value as parameter.
3. In this method the number of rectangle possible will be calculated using the formula  (M(M+1)(N)(N+1))/4
4. Then print the result.

Program:

// JAVA Code to count number of
// rectangles in N*M grid

import java.util.*;

public class Main
{
// Driver method
public static void main(String[] args)
{
//Scanner classobject created
Scanner sc=new Scanner(System.in);
//Taking input of 'n' value
System.out.println("Enter value of N : ");
int n=sc.nextInt();
//Taking input of 'm' value
System.out.println("Enter value of M : ");
int m=sc.nextInt();
//calling the rectangleCount() user defined method
System.out.println("Number of rectangle : "+rectangleCount(n, m));
}

//rectangleCount() method to find the number of rectangles
public static long  rectangleCount(int n, int m)
{
return (m * n * (n + 1) * (m + 1)) / 4;
}
}


Output:

Enter value of N : 2
Enter value of M : 2
Number of rectangle : 9

Don’t stop learning now. Get hold of all the important Java fundamentals with the Simple java program example guide and practice well.