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
- Accept the number of rows (or side length) for the square pattern.
- Use nested loops to iterate through each row and column.
- In the outer loop, check row is the first or last row or if the current column is the first or last column.
- If any of the above conditions are true, print an asterisk (
*
); otherwise, print a space to create the hollow effect. - 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
Code Explanation
- Similar to the solid square pattern, we have a function
printHollowSquare
that takes an integer parametern
representing the size of the square pattern. - The nested loop iterate through each row and column of the square.
- 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.
- 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. - 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.