JavaScript Program to Print Hollow Square Star Pattern

Introduction

A hollow square star pattern consists of stars (*) printed along the boundary of a square, while the inside of the square remains hollow (filled with spaces). This pattern is great for practicing loops and conditional logic in JavaScript.

Problem Statement

Create a JavaScript program that:

  • Accepts the size of the square (number of rows and columns).
  • Prints a hollow square pattern using stars (*).

Example:

  • Input: size = 5
  • Output:
    *****
    *   *
    *   *
    *   *
    *****
    

Solution Steps

  1. Input the Size of the Square: The user specifies the size of the square.
  2. Use Nested Loops: The outer loop handles the rows, and the inner loop handles printing the stars and spaces for each row.
  3. Conditionally Print Stars and Spaces: Print stars at the boundary (first and last row, and first and last columns), while printing spaces inside the square.

JavaScript Program

// Step 1: Input the size of the square
let size = parseInt(prompt("Enter the size of the square: "));

// Step 2: Outer loop for rows
for (let i = 1; i <= size; i++) {
    let output = '';
    
    // Step 3: Inner loop for columns
    for (let j = 1; j <= size; j++) {
        // Step 4: Print stars at the boundary, else print spaces
        if (i === 1 || i === size || j === 1 || j === size) {
            output += '*';
        } else {
            output += ' ';
        }
    }
    
    // Print the output for the current row
    console.log(output);
}

Explanation

Step 1: Input the Size of the Square

  • The program begins by asking the user to input the size of the square. The input is converted to an integer using parseInt().

Step 2: Outer Loop for Rows

  • The outer loop controls how many rows are printed. It runs from 1 to size.

Step 3: Inner Loop for Columns

  • The inner loop controls how many columns are printed in each row. It also runs from 1 to size.

Step 4: Conditional Printing of Stars and Spaces

  • Stars (*) are printed at the boundary of the square:
    • On the first row (i === 1),
    • On the last row (i === size),
    • On the first column (j === 1),
    • On the last column (j === size).
  • Spaces are printed inside the square to create the hollow effect.

Output Example

For size = 5, the output will be:

*****
*   *
*   *
*   *
*****

For size = 4, the output will be:

****
*  *
*  *
****

Conclusion

This JavaScript program prints a hollow square star pattern using nested loops and conditional logic. The stars are printed along the boundary of the square, while spaces are printed inside to create the hollow effect. This exercise is useful for practicing loop control and conditional statements in JavaScript.

Comments