Open In App

JavaScript Program to Print Character Pattern

We will see how can we print character patterns using JavaScript. We will use loop and recursion to print the character pattern. by using those we can understand how the loop and recursion works.

Here are some common approaches:



Approach 1: 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.




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

Approach 2: 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.




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 

Article Tags :