JavaScript Program to Print Double Sided Stair-Case Pattern

This JavaScript program is designed to print a double-sided staircase pattern. A double-sided staircase consists of steps where each step has numbers incrementing from 1 to the current row number on the left side, and then decrementing from the current row number – 1 down to 1 on the right side.

The staircase is printed in a format where each row is displayed on a separate line.

Table of Content

  • Iterative Approach
  • Recursive Approach

Iterative Approach

The JavaScript creates a staircase pattern using alternating spaces and stars. It defines a function pattern(n) with nested loops to manage space and star printing based on row number and parity. Odd rows have one additional space. The result is a staircase pattern. In the driver code, pattern(10) is called to display the pattern.

Example: Generates a right-aligned triangular pattern with alternating row lengths using asterisks. Size is determined by the parameter n (set to 10 in the example).

Javascript




function pattern(n) {
    for (let i = 1; i <= n; i++) {
        let k = i % 2 !== 0 ? i + 1 : i;
 
 
        for (let g = k; g < n; g++) {
            process.stdout.write(" ");
        }
 
        for (let j = 0; j < k; j++) {
            if (j === k - 1) {
                console.log("* ");
            } else {
                process.stdout.write("* ");
            }
        }
    }
}
const n = 10;
pattern(n);


Output

        * * 
        * * 
      * * * * 
      * * * * 
    * * * * * * 
    * * * * * * 
  * * * * * * * * 
  * * * * * * * * 
* * * * * * * * * * 
* * * * * * * * * * 

Recursive Approach

This recursive approach uses two functions: printPattern for printing stars in a row, and pattern for managing rows and spaces. The pattern function iterates through rows, determining the number of spaces and stars needed, and then calls printPattern to print the stars for each row.

Example: Generates an inverted pyramid pattern with alternating row lengths, right-aligned, using asterisks. Size is determined by the parameter n (set to 10 in the example).

Javascript




function printStars(count) {
    if (count <= 0) {
        return;
    }
    process.stdout.write("* ");
    printStars(count - 1);
}
 
function printSpaces(count) {
    if (count <= 0) {
        return;
    }
    process.stdout.write(" ");
    printSpaces(count - 1);
}
 
function pattern(n, row = 1) {
    if (row > n) {
        return;
    }
 
    let k = row % 2 !== 0 ? row + 1 : row;
 
    printSpaces(n - k);
 
    printStars(k);
 
    console.log();
 
    pattern(n, row + 1);
}
 
const n = 10;
pattern(n);


Output

        * * 
        * * 
      * * * * 
      * * * * 
    * * * * * * 
    * * * * * * 
  * * * * * * * * 
  * * * * * * * * 
* * * * * * * * * * 
* * * * * * * * * * 


Contact Us