Day 14 of My DSA Problem Solving Journey

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:

    *
   **
  ***
 ****
*****

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++) {
    // Print spaces
    for (let x = 0; x < n - (i + 1); x++) {
      Stars += " ";
    }
    // Print stars
    for (let j = 0; j < i + 1; j++) {
      Stars += "*";
    }
    Stars += "n"; // New line after each row
  }

  return Stars;
}

console.log(printRightAlignedTriangle(5));



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.

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
sunday-rewind:-pivot-isn’t-a-4-letter-word-–-sunil-parekh

Sunday Rewind: Pivot isn’t a 4-letter word – Sunil Parekh

Next Post
the-power-of-html-–-part-22:-the-future-of-html:-webassembly,-ai-integration,-and-predictions

The Power of HTML – Part 22: The Future of HTML: WebAssembly, AI Integration, and Predictions

Related Posts