Print a Hollow Square Star Pattern in C
To print a hollow square star pattern in C, we use nested loops. The outer loop runs for the number of rows, and the inner loop prints either stars for the border or spaces for the hollow area.
Examples of Printing Hollow Square Patterns
1. Basic Hollow Square Star Pattern
In this example, we print a hollow square pattern of stars where only the border of the square is made up of stars, and the inside remains empty.
main.c
</>
Copy
#include <stdio.h>
int main() {
int n = 5; // Size of square
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;
}
Explanation:
- We declare an integer variable
n
to store the size of the square. - The outer loop (
i
) runs from0
ton-1
, iterating through rows. - The inner loop (
j
) runs from0
ton-1
, iterating through columns. - We use an
if
condition to print stars (*
) when we are at the boundary (i == 0
,i == n-1
,j == 0
, orj == n-1
). Refer: C if-else. - If the condition is false, we print spaces to create the hollow effect.
- After each row,
printf("\n")
moves to the next line.
Output:
* * * * *
* *
* *
* *
* * * * *
2. Hollow Square with Custom Size from User Input
In this example, we allow the user to enter the size of the hollow square, making the program more interactive.
main.c
</>
Copy
#include <stdio.h>
int main() {
int n;
printf("Enter the size of the square: ");
scanf("%d", &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");
}
return 0;
}
Explanation:
- We declare an integer variable
n
to store the user-provided size of the square. - Using
scanf()
, we take user input for the size. - We use nested loops similar to the previous example to create the pattern.
- The outer loop (
i
) iterates over the rows, while the inner loop (j
) iterates over columns. Refer: C For Loop. - The
if
condition checks whether we are at the border of the square and prints stars accordingly. Refer: C if-else. - Spaces are printed inside the square to maintain the hollow effect.
Output (Example User Input: 6):
Enter the size of the square: 6
* * * * * *
* *
* *
* *
* *
* * * * * *
Conclusion
In this tutorial, we learned how to print a hollow square star pattern in C using nested loops. We covered:
- Basic Hollow Square: Printing a fixed-size hollow square.
- Dynamic Size: Taking user input to determine the square size.