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
.
- Print spaces first. The number of spaces is
-
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
ton - 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.