To print an Hourglass Pattern in TypeScript, we follow similar logic to JavaScript using nested loops.
In this example,
printHourglass
that takes the desired number of rows n
as a parameter.for
loops, where the outer loop runs from n
to 1 and the inner loops control the spaces and stars in each row.function printHourglass(n: number): void {
for (let i = n; i >= 1; i--) {
let spaces = ' '.repeat(n - i);
let stars = '*'.repeat(2 * i - 1);
console.log(spaces + stars);
}
for (let i = 2; i <= n; i++) {
let spaces = ' '.repeat(n - i);
let stars = '*'.repeat(2 * i - 1);
console.log(spaces + stars);
}
}
// Example usage
printHourglass(5);
********* ******* ***** *** * *** ***** ******* *********
In this tutorial, we learned How to print Hour Glass Pattern in TypeScript language with well detailed examples.