-1

Instead of 1 index on each row, I want horizontal not vertical returns.

let n = [6];

function staircase() {
  for (let i = 1; i <= n; i++) {
    for (let j = 1; j <= n - i; j++) {
      console.log("0");
    }
    for (let k = 1; k <= i; k++) {
      console.log('#');
    }

  }
}

staircase();

But I need it to render like this. (This works using Java; it's the same logic, but renders differently.)

     #
    ##
   ###
  ####
 #####
######
4
  • this is from the staircase problem on hackerrank. i know how to use .repeat().padstart(). but i just want to get this code to work. Commented Feb 4, 2022 at 14:46
  • 2
    Please don't add new information in comments. There's an Edit button right there. See How to Ask and take the tour. Commented Feb 4, 2022 at 14:49
  • 2
    if you 'know how to use .repeat().padstart()' then just make your loops do what those two methods do, namely pad the start of the string with a repeated substring. Commented Feb 4, 2022 at 14:56
  • Thanks for the info Commented Feb 4, 2022 at 16:49

2 Answers 2

1

console.log prints one line each therefore i put 2 variables to keep the empty string and hash string and after the loops logged the concatenation of the strings

let n = 6

function staircase() {
  for (let i = 1; i <= n; i++) {
    let emptyString = '';
    let hashString = '';
    for (let j = 1; j <= n - i; j++) {
      emptyString += " ";
    }
    for (let k = 1; k <= i; k++) {
      hashString += '#'
    }
    console.log(emptyString + hashString)

  }
}

staircase();

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the info
That code looks good great answer
0

const n = [6] 
for (let i = 1; i <= n; i++) {
     //
    // this array stores the results; 
   //
    const array = [];
  //
    for (let j = 1; j <= n - i; j++) {
      array.push("0");
    }
    for (let k = 1; k <= i; k++) {
      array.push('#');
    }
    // adding `toString`, does the magic
    console.log(array.toString())
}

1 Comment

Thanks for the info

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.