Staircase detail

Klecianny Melo - Feb 16 - - Dev Community

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));
    }
}
Enter fullscreen mode Exit fullscreen mode

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));
Enter fullscreen mode Exit fullscreen mode

#

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));
Enter fullscreen mode Exit fullscreen mode

##

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));
Enter fullscreen mode Exit fullscreen mode

###

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));
Enter fullscreen mode Exit fullscreen mode

####

Share the code, spread knowledge and build the future! 😉

. . . . . . . . . . . . . . . . . . . . . . . .