DEV Community

King coder
King coder

Posted on • Edited on

Day 14 of My DSA Problem Solving Journey

Q1: Print a Right-Aligned Star Triangle Pattern

Problem:

  • Given a number n, print a right-aligned triangle of stars (*) with n rows. The stars in each row should increase from 1 to n, and the triangle should be aligned to the right side by adding spaces before the stars.

Example:

For n = 5, the output should be:

 * ** *** **** ***** 
Enter fullscreen mode Exit fullscreen mode

Approach

  • Use an outer loop to iterate over each row.

  • For each row:

    • Print spaces first. The number of spaces is n - (current_row + 1).
    • Then print stars. The number of stars is current_row + 1.
  • Move to the next line after printing each row.

Example Code

function printRightAlignedTriangle(n) { let Stars = ""; for (let i = 0; i < n; i++) { // X Loop is Responsible For Adding Spacing for (let x = 0; x < n - (i + 1); x++) { Stars += " "; } // J loop is Responsible For Adding Start for (let j = 0; j < i + 1; j++) { Stars += "*"; } Stars += "\n"; // New line after each row } return Stars; } console.log(printRightAlignedTriangle(5)); 
Enter fullscreen mode Exit fullscreen mode

Explanation

  • The outer loop runs from 0 to n - 1, representing each row.

  • Spaces decrease as the row number increases.

  • Stars increase by one each row.

  • Using nested loops, we build the pattern string line by line.

Top comments (0)