C Program to Print Hollow Square Pattern
for loops in C to print a hollow square pattern by printing stars * on the borders and spaces inside, like if (i == 0 || i == n-1 || j == 0 || j == n-1) printf("*"); else printf(" ");.Examples
How to Think About It
* on the first and last rows and columns to form the border. For all other positions inside, print spaces to keep it hollow.Algorithm
Code
#include <stdio.h> int main() { int n = 5; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == 0 || i == n-1 || j == 0 || j == n-1) printf("*"); else printf(" "); } printf("\n"); } return 0; }
Dry Run
Let's trace n=5 through the code to see how the hollow square is printed.
Start outer loop i=0 (first row)
Print stars for all columns j=0 to 4 because i=0 is the first row.
i=1 (second row)
Print star at j=0 (first column), spaces for j=1 to 3, star at j=4 (last column).
i=2 (third row)
Same as i=1: star at borders, spaces inside.
i=3 (fourth row)
Same as i=1 and i=2.
i=4 (last row)
Print stars for all columns because i=4 is the last row.
| Row (i) | Column (j) | |
|---|---|---|
| 0 | 0-4 | ***** |
| 1 | 0 | * |
| 1 | 1-3 | |
| 1 | 4 | * |
| 2 | 0 | * |
| 2 | 1-3 | |
| 2 | 4 | * |
| 3 | 0 | * |
| 3 | 1-3 | |
| 3 | 4 | * |
| 4 | 0-4 | ***** |
Why This Works
Step 1: Print border stars
The condition i == 0 || i == n-1 || j == 0 || j == n-1 checks if the current position is on the border to print stars.
Step 2: Print spaces inside
For positions not on the border, printing spaces creates the hollow effect inside the square.
Step 3: Nested loops for rows and columns
Two loops let us visit every position in the square grid row by row and column by column.
Alternative Approaches
#include <stdio.h> int main() { int n = 5, i = 0, j; while (i < n) { j = 0; while (j < n) { if (i == 0 || i == n-1 || j == 0 || j == n-1) printf("*"); else printf(" "); j++; } printf("\n"); i++; } return 0; }
#include <stdio.h> void printHollowSquare(int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == 0 || i == n-1 || j == 0 || j == n-1) printf("*"); else printf(" "); } printf("\n"); } } int main() { printHollowSquare(5); return 0; }
Complexity: O(n^2) time, O(1) space
Time Complexity
The program uses two nested loops each running n times, so it runs in O(n^2) time.
Space Complexity
Only a few variables are used; no extra space grows with input size, so space is O(1).
Which Approach is Fastest?
All approaches use nested loops and have the same time and space complexity; differences are mainly in code style.
| Approach | Time | Space | Best For |
|---|---|---|---|
| For loops | O(n^2) | O(1) | Simple and clear code |
| While loops | O(n^2) | O(1) | Alternative loop style |
| Function encapsulation | O(n^2) | O(1) | Reusable and organized code |