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.
In this example,
printHollowSquare
that takes the side length n
as a parameter.for
loops, one for rows and one for columns, to iterate through each cell of the square.*
) for the border and spaces (
) for the inside.printHollowSquare
with the desired side length to print the pattern.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);
***** * * * * * * *****
In this tutorial, we learned How to print Hollow Square Pattern in TypeScript language with well detailed examples.