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)
'# '
'## '
'### '
'####'
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++)
}
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 = ' ';
}
}
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++) {
}
}
}
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 += ' ';
}
}
}
}
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)
}
}
staircase(6)
#
##
###
####
#####
######
I hope you will find this helpful practicing data structure and algorithms.
Top comments (4)
Real smooth. But you could cut down on the second loop and achieve it this way too.
but time complexity would be same because of .repeat
Great.
You can make even more shorter like this
Thank you so much for this !!