A hollow square of stars is a square pattern where only the borders are printed with stars, leaving the inner part empty. Printing such patterns helps beginners understand nested loops and conditional statements in C.
Understanding The Problem
The program should take the number of rows (or columns) as input and print a square of stars where only the first and last rows, as well as the first and last columns, contain stars. Conditional statements are used to differentiate between border and inner positions.
Steps to Solve the Problem:
- Take the size of the square as input.
- Use an outer loop to iterate through rows.
- Use an inner loop to iterate through columns.
- Print a star if the current position is on the border; otherwise, print a space.
- Move to a new line after completing each row.
Solution: Using Nested Loops with Conditionals
Nested loops along with conditional checks allow creating the hollow square pattern.
#include <stdio.h>
int main() {
int size;
printf("Enter the size of the square: ");
scanf("%d", &size);
for(int i = 1; i <= size; i++) {
for(int j = 1; j <= size; j++) {
if(i == 1 || i == size || j == 1 || j == size) {
printf("*");
} else {
printf(" ");
}
}
printf("\n");
}
return 0;
}
In this program, the outer loop controls rows and the inner loop controls columns. Stars are printed for the first and last rows or columns, while spaces are printed for inner positions. This creates a hollow effect for the square.

FAQs
Q1: Can this pattern use a character other than *
?
Yes, any character can replace *
to create the hollow square with different symbols.
Q2: Can the square size be decimal?
No, the size must be an integer since each row and column represents discrete positions.
Q3: Can we create a hollow rectangle instead of a square?
Yes, by using separate values for rows and columns, you can print a hollow rectangle.
Conclusion
This program demonstrates how to print a hollow square of stars using nested loops and conditionals. By controlling the positions where stars are printed, a visually appealing hollow square is formed. The logic can also be adapted to hollow rectangles, hollow triangles, and other patterns.
References & Additional Resources
- C Programming Tutorial – Covers loops, nested loops, and pattern printing in C.
- GeeksforGeeks – Pattern Programs in C – Examples of solid and hollow patterns using loops.
- TutorialsPoint – C Loops – Explanation of nested loops and conditional printing in C.