Exercise 9: Printing Steps

Directions

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 step has spaces on the right hand side!

Examples

steps(2)
      '# '
      '##'
  steps(3)
      '#  '
      '## '
      '###'
  steps(4)
      '#   '
      '##  '
      '### '
      '####'

Guidelines

Two solutions:-

1) Iterative (recommended)

  • Pseudo code

03_09

  • Should make multiple strings on each stair and console log each of them
  • NOT assembling one string and then escaping it with a newline character (\n) at the end

2) Recursive

  • Pseudo code

03_13

  • Faster to derive from iterative solution than derive out of thin air

Solution

In [1]:
function steps(n) {
  for(let row=0; row<n; row++){
      let stair = "";
    for (let col=0; col<n; col++){
      if (col <= row){
        stair += "#";  
      } else
        stair += " ";
    }
    console.log(stair);
  }
}

Alternative Solution

In [2]:
function steps(n, row = 0, stair = "") {
  if (n === row){
    return;
  }

  if (n === stair.length){ // at the end of the row
    console.log(stair);
    return steps(n, row + 1);
  }

  const add = stair.length <= row? "#" : " "; //ternary operator

  steps(n, row, stair + add);
}
In [3]:
steps(2)
# 
##
In [4]:
steps(3)
#  
## 
###
In [5]:
steps(4)
#   
##  
### 
####