Reputation: 749
let printTriangle = (num) => {
for ( let i = 0; i < num; i++) {
for (let j = 0; j <= i; j++) {
num += '*';
}
num += "\n"
}
}
console.log(printTriangle(5));
I have a simple question although i cannot manage to resolve this problem. Hope you can help, how i should fix my code to make output:
*
**
***
****
*****
Upvotes: 1
Views: 279
Reputation: 1773
this is because you are appending the desired string in num i.e a number resulting in wrong output. You should rather initialize another variable inside your function and append * into it. Also, you are not returning anything from this function that's why instead of some value undefined is getting logged.
printTriangle = num => {
let result = "";
for (let i = 0; i < num; i++) {
for (let j = 0; j <= i; j++) {
result += "*";
}
result += "\n";
}
return result;
};
console.log(printTriangle(5));
There are many more ways to do this, you should try some other efficient ways also.
Upvotes: 1
Reputation: 3426
We can use the repeat
method for this:
function triangle(n) {
let acc = "";
for (let i = 1; i <= n; i++) {
acc = `${acc}${"*".repeat(i)}\n`;
}
return acc;
}
console.log(triangle(5));
Upvotes: 1
Reputation: 917
let printTriangle = (num) => {
let result = "";
for ( let i = 0; i < num; i++) {
for (let j = 0; j <= i; j++) {
result += '*';
}
result += "\n";
}
return result;
}
console.log(printTriangle(5));
Upvotes: 1