JavaScript Program to Print Character Pattern

Printing a character pattern involves generating and displaying a structured arrangement of characters, often in a specific geometric shape such as a triangle or square. This process typically includes using loops to systematically place characters in rows and columns based on given rules.

Here are some common approaches:

Table of Content

  • Using Nested Loop
  • Using Recursion
  • Using Array and Join

Using Nested Loop

Using nested loops, iterate over rows and columns, incrementally printing based on row number. The outer loop controls rows, inner loop controls columns, printing Character for each column up to the row number.

Example: The function myPatternFunction iterates over rows, incrementally printing Characters based on row number, achieving a pattern with increasing lengths per row.

Javascript
function myPattern(rows, startCharacter) {
    const startCharCode = startCharacter.charCodeAt(0);
    for (let i = 0; i < rows; i++) {
        let pattern = '';
        for (let j = 0; j <= i; j++) {
            pattern += String
                .fromCharCode(startCharCode + j);
        }
        console.log(pattern);
    }
}

myPattern(5, 'A');

Output
A
AB
ABC
ABCD
ABCDE

Using Recursion

Recursively print a character pattern by appending a Character in each recursive call, incrementing the row number. The base case returns if the row exceeds the limit. Each call prints the pattern with an additional Character compared to the previous row.

Example: We will print a pattern of Character with increasing length per row, up to the specified number of rows (in this case, 5), using recursion.

Javascript
function myPattern(rows, row = 1,
    pattern = '') {
    if (row > rows) return;
    pattern += String.fromCharCode(64 + row) + ' ';
    console.log(pattern);
    myPattern(rows, row + 1, pattern);
}

myPattern(5);

Output
A 
A B 
A B C 
A B C D 
A B C D E 

Using Array and Join

This approach builds a character pattern using nested loops and arrays. Each line is created as an array of characters, joined into a string, and stored in another array. The array of lines is then printed. Character codes are cycled from ‘A’ to ‘Z’.

Example : In this example the printPattern3 function generates a pattern of increasing lines of alphabetic characters, resetting from ‘Z’ to ‘A’ if needed. It prints each line, forming a triangular pattern of letters for `n` lines.

JavaScript
function printPattern3(n) {
    let charCode = 65;
    let arr = [];
    for (let i = 0; i < n; i++) {
        let line = [];
        for (let j = 0; j <= i; j++) {
            line.push(String.fromCharCode(charCode++));
            if (charCode > 90) charCode = 65;
        }
        arr.push(line.join(''));
    }
    arr.forEach(line => console.log(line));
}

printPattern3(5);

Output
A
BC
DEF
GHIJ
KLMNO




Contact Us