Reputation: 13
I have a javascript question, I want to make a Triangle like this
*
**
***
****
*****
this is my code which makes opposite direction
for(let i = 0;i<=5;i++){
let str = "";
for(let j = 0;j<i;j++){
str += "*";
}
console.log(str)
}
I wanna use for loop to make this triangle down bellow instead of using "repeat".
for(let i = 0;i<=5;i++){
let str = "";
str = " ".repeat(5-i);
str2 = "*".repeat(i);
console.log(str+str2);
}
Upvotes: 1
Views: 135
Reputation: 2570
You can write it like this:
for(let i = 0;i<=5;i++){
let str = "";
for(let j = i;j<5;j++){
str += " ";
}
for(let j = 0;j<i;j++){
str += "*";
}
console.log(str)
}
This method can be used in all other programming languages, cause there's no special js syntax or special js built-in function.
Upvotes: 0
Reputation: 11001
Use padStart
method
for (let i = 0; i <= 5; i++) {
let str = "";
for (let j = 0; j < i; j++) {
str += "*";
}
console.log(str.padStart(5, " "));
}
Further simplify to one liner
for (let i = 0; i <= 5; i++) {
console.log('*'.repeat(i).padStart(5, " "));
}
Upvotes: 2
Reputation: 14891
You could use for loop with ternary operator
for (let i = 0; i <= 5; i++) {
let str = "";
for (let j = 0; j <= 5; j++) {
str += j < 5 - i ? " " : "*";
}
console.log(str);
}
Upvotes: 2