Loading...

Introduction

Hollow square pattern printing is a classic programming task that challenges developers to create a square pattern with a hollow center using asterisks or any other character. This exercise not only helps in understanding the basics of nested loops but also provides a hands-on experience in controlling the flow of execution to create intricate designs.

Understanding the Pattern

A hollow square pattern consists of an outer square with sides formed by asterisks (*) and an inner square left empty.

Algorithm

  1. Accept the number of rows (or side length) for the square pattern.
  2. Use nested loops to iterate through each row and column.
  3. In the outer loop, check row is the first or last row or if the current column is the first or last column.
  4. If any of the above conditions are true, print an asterisk (*); otherwise, print a space to create the hollow effect.
  5. Move to the next line after completing a row.

Code Implementation

#include <iostream>

void printHollowSquarePattern(int n) {
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
        	// Print '*' only for the first and last rows, and the first and last columns
            if (i == 0 || i == n - 1 || j == 0 || j == n - 1)
                std::cout << "* ";
            else
                std::cout << "  "; // Print two spaces for the hollow part
        }
        std::cout << "\n";
    }
}

int main() {
    int size;
    std::cout << "Enter the size of the hollow square pattern: ";
    std::cin >> size;

    printHollowSquarePattern(size);

    return 0;
}

Output

hollow_square_star_pattern

Code Explanation

  1. Similar to the solid square pattern, we have a function printHollowSquare that takes an integer parameter n representing the size of the square pattern.
  2. The nested loop iterate through each row and column of the square.
  3. Inside the inner loop, a conditional statement checks whether the current position is on the border (first or last row/column) or in the hollow center. If true, an asterisk is printed; otherwise a space is printed to create the hollow effect.
  4. The conditional check (if ( == 0 || i == n-1 || j == 0 || j = n-1)) ensures that only the first and last rows, as well as the first and last columns, are filled.
  5. After printing each row, a newline character (\n) is added to move to the next line.

Complexity Analysis

Time Complexity: The time complexity of the hollow square printing algorithm is O(n^2), where n is the size of the square. The nested loops iterate n times, and the conditional check within the loops has constant time complexity.

Space Complexity: The space complexity is O(1), as the program uses a constant amount of additional space regardless of the input size.