Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cycle with Repeat

I faced this problem: I need to write a program that will display a staircase in the console using repeat. And the staircase should be displayed in both directions.

The question is, can I add a method repeat to the function, so that it outputs to the console in steps of characters, like here, for example:

'      #'
'     ###'
'    #####'
'   #######'
'  #########'
' ###########'

Please advise me, or just give me a hint in what direction to dig. Below is the cycle that I use.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let i = 0;
let max = 6;
while (i < max) {
  let space = "";
  let tree = "";
  for (let j = 0; j < max - i; j++) space += " ";
  for (let j = 0; j < 2 * i + 1; j++) tree += "#";
  console.log(space + tree)
  i++
}

>Solution :

I am not very clear about your question. The following codes provide the same result as yours by the means of repeat function (String.prototype.repeat).

let layer = 6;
for (let i = 0; i < layer; ++i) {
    console.log(' '.repeat(layer - i) + '#'.repeat(1 + i * 2));
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading