Generating a Star Pattern with TypeScript
In this tutorial, we’ll explore a simple yet interesting coding exercise: generating and printing a star pattern using TypeScript. This pattern is often used in programming courses to teach the basics of nested loops and pattern formation. By the end of this article, you’ll have a clear understanding of how to create such patterns programmatically.
Prerequisites
Before we dive into the code, ensure that you have TypeScript and Node.js installed on your machine. If you haven’t already, you can download and install them from the official websites: TypeScript and Node.js.
Code
function starPattern (rows:number) : void{
for(let i:number = 0 ; i<rows;i++){
let pattern:string = '';
for(let j:number =0 ;j<=i;j++){
pattern += '* ';
}
console.log(pattern);
}
}
let Rows:number = 5
starPattern(Rows)
Output
*
**
***
****
*****
How It Works
Let’s break down the code step by step:
- We define a TypeScript function called
starPattern
that takes a single argument,rows
, which represents the number of rows in our star pattern. - Inside the function, we use a
for
loop with the counter variablei
to iterate through each row of the pattern. It starts from0
and continues as long asi
is less than the specified number of rows. - For each row, we initialize an empty string called
pattern
. - Within an inner
for
loop, controlled by the counter variablej
, we build the star pattern. The inner loop starts from0
and runs untilj
is less than or equal toi
. During each iteration, we add a star followed by a space to thepattern
string. - After constructing the
pattern
for the current row, we print it to the console usingconsole.log
. - The outer loop repeats this process for the desired number of rows, ultimately creating a star pattern.
Running the Code
To see this star pattern in action, you can specify the number of rows by setting the numRows
variable to your desired value. Then, simply run the script using Node.js.
Conclusion
In this tutorial, we’ve explored how to create a star pattern using TypeScript. This exercise is a great way to practice loop structures and string manipulation in programming. You can customize the pattern by adjusting the number of rows, allowing you to create a variety of different patterns for various applications.
Now that you understand the code, feel free to experiment with different patterns and row counts to enhance your TypeScript skills. Happy coding!