Back to Patterns
Alternating Rectangle Pattern
Pattern Result
********** ** ***** ** * * ** * * * ** * * ** ***** ** **********
Code Implementation
Explanation
The Alternating Rectangle Pattern creates a series of concentric rectangles with alternating characters (asterisks and spaces). The pattern starts with an outer border of asterisks, followed by a border of spaces, then another border of asterisks, and so on. The algorithm ensures that n is odd to create a symmetrical pattern. It creates a 2D array filled with spaces and then fills it layer by layer, starting from the outermost layer and moving inward. For each layer, it determines the character (asterisk or space) based on the layer number and fills the top, bottom, left, and right borders of that layer with the character. Finally, it converts the 2D array to a pattern by joining each row into a string.