How to print Hollow Square Pattern in TypeScript


How to print Hollow Square Pattern in TypeScript ?

Answer

To print a Hollow Square Pattern in TypeScript, you can follow a similar approach to JavaScript using nested loops and conditions to control the printing of stars and spaces.



✐ Examples

1 Print Hollow Square Pattern

In this example,

  1. We define a function named printHollowSquare that takes the side length n as a parameter.
  2. We use two nested for loops, one for rows and one for columns, to iterate through each cell of the square.
  3. Within the loops, we use conditions to check if we are at the border or inside the square, printing stars (*) for the border and spaces ( ) for the inside.
  4. Finally, we call printHollowSquare with the desired side length to print the pattern.

TypeScript Program

function printHollowSquare(n: number): void {
    for (let i = 0; i < n; i++) {
        let row = '';
        for (let j = 0; j < n; j++) {
            if (i === 0 || i === n - 1 || j === 0 || j === n - 1) {
                row += '*';
            } else {
                row += ' ';
            }
        }
        console.log(row);
    }
}

const sideLength: number = 5;
printHollowSquare(sideLength);

Output

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

Summary

In this tutorial, we learned How to print Hollow Square Pattern in TypeScript language with well detailed examples.




More TypeScript Pattern Printing Tutorials

  1. How to print Left Half Pyramid Pattern in TypeScript ?
  2. How to print Right Half Pyramid Pattern in TypeScript ?
  3. How to print Pyramid Pattern in TypeScript ?
  4. How to print Rhombus Pattern in TypeScript ?
  5. How to print Diamond Pattern in TypeScript ?
  6. How to print Hour Glass Pattern in TypeScript ?
  7. How to print Hollow Square Pattern in TypeScript ?
  8. How to print Hollow Pyramid Pattern in TypeScript ?
  9. How to print Hollow Inverted Pyramid Pattern in TypeScript ?
  10. How to print Hollow Diamond Pattern in TypeScript ?
  11. How to print Floyd's Trianlge Pattern in TypeScript ?
  12. How to print Pascal's Triangle Pattern in TypeScript ?