I am trying to write a function to return a reverse right triangle but I am having trouble figuring out where I am going wrong.
function triangle(num) {
let star = ""
for (let i = num; i >= 1; i--) {
for (let j = num; j >= 1; j--) {
star += "*" + "\n"
}
}
return star
}
console.log(triangle(6));
My problem is I am having trouble getting the whole function to return a string of * in the form of a reverse triangle. I believe I have concocted the '\n' in the wrong place as well but I am not sure where to change it to.
I am receiving back this:
console.log(triangle(6));
************************************
I am supposed to receive back this:
console.log(triangle(6));
"******\n*****\n****\n***\n**\n*"
I am supposed to concatenate \n to the string output.
-THIS IS WHERE I AM HAVING THE PROBLEM-
I think this is what you want:
function triangle(num) {
let star = ""
for (let i = num; i >= 1; i--) {
for(let j = i; j >= 1; j--) {
star += "*"
}
if(i !== 1) {
star += "\\n"
}
}
return star
}
console.log(triangle(6));
See example here: https://codepen.io/bj-rn-nyborg/pen/gOwOdxR
I moved the +"\n"
to the outer loop, and also initialized let j = i
instead num
How do I create a runnable stack snippet?
Simply post executable js code. 😊 The code in you example is also a runnable snippet.
This fixed making it into a triangle but I still need the whole thing inside of a string.
I have updated the codepen. It now also writes the triangle as a string to the DOM: codepen.io/bj-rn-nyborg/pen/gOwOdxR
\n is a hidden character, it is already in the code i build. That is what causes the new line. If you want to display it as a string, you will simply need to escape it, you can do it with a backslash, like this:
star += "\\n"
I have updated the codepen too. 😊