I have a javascript question, I want to make a Triangle like this
JavaScript
x
6
1
*
2
**
3
***
4
****
5
*****
6
this is my code which makes opposite direction
JavaScript
1
8
1
for(let i = 0;i<=5;i++){
2
let str = "";
3
for(let j = 0;j<i;j++){
4
str += "*";
5
}
6
console.log(str)
7
}
8
I wanna use for loop to make this triangle down bellow instead of using “repeat”.
JavaScript
1
7
1
for(let i = 0;i<=5;i++){
2
let str = "";
3
str = " ".repeat(5-i);
4
str2 = "*".repeat(i);
5
console.log(str+str2);
6
}
7
Advertisement
Answer
You can write it like this:
JavaScript
1
11
11
1
for(let i = 0;i<=5;i++){
2
let str = "";
3
for(let j = i;j<5;j++){
4
str += " ";
5
}
6
for(let j = 0;j<i;j++){
7
str += "*";
8
}
9
console.log(str)
10
}
11
This method can be used in all other programming languages, cause there’s no special js syntax or special js built-in function.