You are currently viewing Print a Star Pattern in TypeScript

Print a Star Pattern in TypeScript

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:

  1. We define a TypeScript function called starPattern that takes a single argument, rows, which represents the number of rows in our star pattern.
  2. Inside the function, we use a for loop with the counter variable i to iterate through each row of the pattern. It starts from 0 and continues as long as i is less than the specified number of rows.
  3. For each row, we initialize an empty string called pattern.
  4. Within an inner for loop, controlled by the counter variable j, we build the star pattern. The inner loop starts from 0 and runs until j is less than or equal to i. During each iteration, we add a star followed by a space to the pattern string.
  5. After constructing the pattern for the current row, we print it to the console using console.log.
  6. 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!

Leave a Reply