How to print star Pattern in the shape of Bar Graph in Java

Hi coders! Today we are going to learn how to print star pattern (*) in the shape of a bar graph in Java. Pattern printing is a very interesting and HOT topic for coding interviews. The bar graph pattern will look like this:-
The input will be given in the form of an array= {4, 3, 4, 5, 7}, the output will be like this:-

print star Pattern in the shape of Bar Graph in Java

 

Also have a look at: Various Star Pattern Programming in Java

Method 1: Steps to follow
1) First, find the max number in the input array(max=7, row=7), This will give the no. of rows for the desired 2D matrix.
2) No. of elements in the input array (n=5, col=5) will give no. of columns for the desired 2D matrix.
3) First, we will fill the desired print in a 2D array in a horizontal way, and then we will print the 2D array in transpose way. In that, we will first print all the spaces and after sufficient spaces ( * )  will be printed.

star pattern in bar shape java

After transpose, the desired print will be:-
star pattern print bar java

Program to print star Pattern in the shape of Bar Graph in Java

public class bargraph {

  public static void main(String[] args) {
    int arr[]= {4,3,4,5,7};
    int len=arr.length;
    int max=0;
    
    for(int i=0;i<len;i++)   //find max of array
    {
      if (arr[i]>max)
      {
        max=arr[i];
      }
    }

    char [][]dis1=new char[len][max];

    for(int j=0;j<len;j++)   //store the array in horizontal order
    { 
      for(int i=0;i<max-arr[j];i++)	 
       dis1[j][i]=' ';
    
      for(int k=max-arr[j];k<max;k++)
      {	dis1[j][k]='*';
      
      }
        
    }
    
    for(int i=0;i<max;i++)  //print the array in transpose order 
    {
      for(int j=0;j<len;j++)
      System.out.print(dis1[j][i]+" ");	
      System.out.println();
    }
  }

Output:-

final pattern output

There are other methods too to print this pattern. You can also change the input array size and elements to print various bar graph pattern.

Hope you understand the code.

Leave a Reply

Your email address will not be published. Required fields are marked *