Printing Staircase in JavaScript

tadea

Tadea Simunovic

Posted on May 23, 2020

Printing Staircase in JavaScript

For today's challenge we will create a function staircase, visual stairs made of pound symbol(#).
Let's take a look at the challenge description.

Challenge

Write a function that accepts a positive number N.
The function should console log a step shape
with N levels using the # character. Make sure the
the step has spaces on the right-hand side!
--- Examples
staircase(2)
'# '
'##'
staircase(3)
'#  '
'## '
'###'
staircase(4)
'#   '
'##  '
'### '
'####'
Enter fullscreen mode Exit fullscreen mode

This challenge supposed to form visual stairs made of # symbol. An argument number is a number of lines we want to pass in. If we have one step, we need to add a space (' ') after #.
We will reflect the current row with "i" and column with "j". To start we will for loop through rows from 0 to n.

function staircase(n) {
  for (let i = 0; i < n; i++)
}
Enter fullscreen mode Exit fullscreen mode

For each row, we are considering we will create an empty string step

function staircase(n) {
  for (let i = 0; i < n; i++) {
      let step = ' ';
  }
}
Enter fullscreen mode Exit fullscreen mode

Then we will iterate from 0 to n, through columns with for loop.

function staircase(n) {
  for (let i = 0; i < n; i++) {
      let step = ' ';

   for (let j = 0; j < n; j++) {
   }
  }
}
Enter fullscreen mode Exit fullscreen mode

Then inside of the inner loop, we will say, if the current column that we are looking at is equal to or less than the current row we want to add a pound(#) to step, else, we will add space (' ').

function staircase(n) {
  for (let i = 0; i < n; i++) {
      let step = ' ';

   for (let j = 0; j < n; j++) {
      if (j <= i) {
        step += '#'
     } else {
        step += ' ';
     }
   }
  }
}
Enter fullscreen mode Exit fullscreen mode

We will console.log(step) inside of our for loop, because we want to console.log n number of times.

function staircase(n) {
  for (let i = 0; i < n; i++) {
      let step = ' ';

   for (let j = 0; j < n; j++) {
      if (j <= i) {
        step += '#'
     } else {
        step += ' ';
     }
   }
   console.log(step)
  }
}
Enter fullscreen mode Exit fullscreen mode
staircase(6)
#
##
###
####
#####
######
Enter fullscreen mode Exit fullscreen mode

I hope you will find this helpful practicing data structure and algorithms.

💖 💪 🙅 🚩
tadea
Tadea Simunovic

Posted on May 23, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related