Prepare your favorite cup of coffee because we are about to enter the fantastic world of Staircases.
What is a Staircase?
A staircase in English is a visual representation of a staircase, formed by a series of steps. The staircase has an user-specified size and the step is represented by the #
character.
For example, a 3-step staircase will have the following format:
#
##
###
Let's learn how to build a function that takes a number n and prints a staircase with n steps. To do this, we will use the following example, where a staircase of n = 4 is determined and then we have the expected result:
This is a staircase of size n = 4:
#
##
###
####
For this we will consider the space as the character and the step of the ladder as
#
.
// Function that prints a staircase with n steps
function staircase(n) {
// Constant representing the space character
const space = ' ';
// Constant representing the stair step character
const hash = '#';
// Loop to display the staircase
for (let i = 0; i < n; i++) {
// `space.repeat(n - i - 1)`: will display a certain amount of space characters
// `hash.repeat(i + 1)`: will display a certain number of hash characters
console.log(space.repeat(n - i - 1) + hash.repeat(i + 1));
}
}
Running the staircase
function with n = 4 we will have:
staircase(4);
#
##
###
####
Checking the execution of the for loop
For n = 4, we will have i = 0
in the first execution of the loop:
console.log(space.repeat(n - i - 1) + hash.repeat(i + 1));
console.log(space.repeat(4 - 0 - 1) + hash.repeat(0 + 1));
console.log(space.repeat(3) + hash.repeat(1));
#
The second execution of the i = 1
loop:
console.log(space.repeat(n - i - 1) + hash.repeat(i + 1));
console.log(space.repeat(4 - 1 - 1) + hash.repeat(1 + 1));
console.log(space.repeat(2) + hash.repeat(2));
##
The third execution of the i = 2
loop:
console.log(space.repeat(n - i - 1) + hash.repeat(i + 1));
console.log(space.repeat(4 - 2 - 1) + hash.repeat(2 + 1));
console.log(space.repeat(1) + hash.repeat(3));
###
The fourth and final execution of the i = 3
loop:
console.log(space.repeat(n - i - 1) + hash.repeat(i + 1));
console.log(space.repeat(4 - 3 - 1) + hash.repeat(3 + 1));
console.log(space.repeat(0) + hash.repeat(4));
####
Share the code, spread knowledge and build the future! 😉
Top comments (10)
Hy,
I was wandering about the output. You should put the printout in the listings, as the markdown kills all the leading spaces. Your result should look like this:
Anyway, this is also a nice case to learn some recursion:
If you like the freak style, you can also create a "one-liner":
It works, try it out
Thank you for this contribution @efpage! 😁
nice article ❤️
Thank you! 😁
Wow! Nice article!
Thank you! 😁
nice article! thanks for sharing with us 😊
Thank you my friend! 😁
Another one good article o/
Thank you! 😁