# Java Program to Print Hexagonal Number Pattern

## Program to Print Hexagonal Number Pattern

In the previous article, we have discussed Java Program to Print Double-Sided Stair Case Number Pattern

In this article we will see how to print hexagonal number pattern.

Example:

When the size taken :   8
0
1 1
2   2
3     3
4       4
5         5
6           6
7             7
0             0
1             1
2             2
3             3
4             4
5             5
7             7
6           6
5         5
4       4
3     3
2   2
1 1
0

Access the Simple Java program for Interview examples with output from our page and impress your interviewer panel with your coding skills.

### Approach  to Print Hexagonal Number Pattern

• Solve the hexagonal in 3 different parts.
• First take a for loop to print upper part of hexagonal which is the inverted ‘v’ type like ^
• Second take a for loop to print middle part of hexagonal which is two vertical bars like ||
• Third take a for loop to print lower part of hexagonal which is the ‘v’ type like v

### Java Code to Print Hexagonal Number Pattern

import java.util.*;
public class  Main
{
public static void main (String[] args)
{
Scanner sc=new Scanner(System.in);
// Asks for user input to enter any number
// Where that number of stars will be printed
// in a side of hexagonal pattern
System.out.print("Enter the number:");
int side = sc.nextInt();

int len = 2 * side - 1;

// Printing upper part
for (int i = 0; i < side; i++)
{
int element = i + side;

// prints the number and spaces
for (int k = 0; k < element; k++)
{
// printing the number
if ((k == side + i - 1) || (k == side - i - 1))
System.out.print(i);
// printing the space
else
System.out.print(" ");
}
System.out.print("\n");
}

// Printing middle part
//  Two vertical lines will be printed with middle space
for (int i = 0; i < side - 2; i++)
{
for (int j = 0; j < len; j++)
{
// printing number
if (j == 0 || j == len - 1)
System.out.print(i);
// printing space
else
System.out.print(" ");
}
System.out.print("\n");
}

// Printing lower part
int r = side - 1;
for (int i = r; i >= 0; i--)
{
int elem = i + side;
for (int k = 0; k < elem; k++)
{
// printing the number
if ((k == side + i - 1) || (k == side - i - 1))
System.out.print(i);
// printing the space
else
System.out.print(" ");
}
System.out.print("\n");
}
}

}
Output:

Enter the number:    8
0
1 1
2   2
3     3
4       4
5         5
6           6
7             7
0             0
1             1
2             2
3             3
4             4
5             5
7             7
6           6
5         5
4       4
3     3
2   2
1 1
0

Are you seeking professional help for coding in the Java programming language? The tutorial of Java Programming Examples for beginners and experts will strongly improve your coding skills then you can program for any logic in Java.