Java Programming : Hollow Rectangle star Pattern

Example

Input
5
Output
***** 
*   * 
*   * 
*   * 
*****

Required to Know

Use of Variables, Use of different operators like assignment or arithmetic operators, Use of methods like System. out. print(), and use of for loop, use of nested for loop, and Use of Data types

Steps

  1. Take range as input from the user.

  2. Run the outer loop till the given range. Inside the outer loop, we also need to run another loop till the given range only.

  3. Inside the another loop, we need to provide a condition to print the star in each column of a row.

  4. In the outer loop which is the main loop also, we need to use the next line statement. So that it moves to the next line.

How the loop should be structured along with the condition

  1. Outer loop : - for(i=1;i<=n;i++) -> rows

  2. Inside the outer loop : - for(j=1;j<=n;j++) -> columns

  3. Condition : - if(i==1 || i==n || j==1 || j==n)

    1. i==1 or i==n means : - first row and last row

    2. j==1 or j==n means : - first column and last column

  4. Print star statement : - System.out.print("*");

  5. Print star in the next line statement : - System.out.println(" ")

Program

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