settingsAccountsettings
Menusettings

Q: Triangle of Stars - JavaScript task

+2 votes

Write a JS function that outputs a triangle made of stars with variable size, depending on an input parameter. Look at the examples to get an idea. The input comes as a single number argument.

Examples:

Input:
1

Output:

*

Input:
2

Output:

*
**
*

Input:
5

Output:

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

The output is a series of lines printed on the console, forming a triangle of variable size.

asked in JavaScript category by user ak47seo
edited by user ak47seo

1 Answer

+3 votes

Here is my js program. Note line 10 - the reverse loop:

function printTriangle(n) {
    function printStars(count=n) {//by default count=n
        console.log("*".repeat(count));
    }

    for (let i = 1; i <= n; i++) {
        printStars(i);
    }

    for (let i = n - 1; i > 0; i--) {//reverse loop
        printStars(i);
    }
}

printTriangle(6);

 

answered by user andrew
Thanks! nice solution!
...