Java Program for Hollow Rectangle Star Pattern​

Printing Hollow Rectangle Star Pattern

In this program we’re going to code hollow rectangle star  pattern program .

The logic of this program is to take input from user as row and coloum and store it in variable named as row and col  . After this take a for loop start from i=1 to i++ and then inside main loop take one inner loop start from j=1 to j++ and then write if statement as if(i==1 or i==col) or (j==1 or j==col) and then take a star statement then take a else part and then print space statement then write line changement statement 

Hollow Rectangle Star Pattern

Algorithm:

  • Take the number of rows and columns as input from the user ( length and breadth of the rectangle) and store it in two different variables. (‘row’ and ‘col’ in this case)
  • Run a loop ‘row’ number of times to iterate through all the rows. From i=1 to i<=row. The loop should be structured as for (int i = 1; i <= row; i++)
  •  Run a nested loop ‘col’ times to iterate though each column of a row. From j=1 to j<=col. The loop should be structured as for(j=1 ; j<=col ; j++).
  • Inside the nested loop print star if  i==1 or i==col  or j=1 or j==col
  • Else print a white-space.
  • Inside the main loop print a newline to move to the next line.

Code in Java:

import java.util.Scanner;
public class Pattern1 {
     public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter row and col");
		int row = sc.nextInt();
		int col = sc.nextInt();
				
    	for (int i = 1; i <= row; i++) {
			for (int j = 1 ; j <= col; j++) 
				if((i==1 || i==col) || (j==1 || j==col))
				   System.out.print("*");
				else
			       System.out.print(" ");
			
			System.out.println();
		}
     }
}

This code is contributed by Shubham Nigam (Prepinsta Placement Cell Student) 

2 comments on “Java Program for Hollow Rectangle Star Pattern​”