C (programming language)
C program to print hollow square star pattern
C Program to Print Hollow Square Star Pattern
Introduction
This guide will explore the creation of a C program that generates a visual pattern resembling a hollow square composed of stars (*
). We’ll delve into the logic, code structure, and key steps involved in crafting this pattern.
Understanding the Pattern
- Shape: The pattern forms a square with empty spaces inside, creating a hollow appearance.
- Composition: Stars (
*
) are used to construct the borders of the square. - Arrangement: The stars are positioned in specific rows and columns to achieve the desired hollowness.
Steps to Implement
- Include Necessary Header:
C
#include <stdio.h>
- Declare Variables:
C
int rows, i, j;
- Get Input for Number of Rows:
C
printf("Enter the number of rows: ");
scanf("%d", &rows);
- Use Nested Loops to Print the Hollow Square:
C
for (i = 1; i <= rows; i++) {
// Print stars for the first and last column of each row
for (j = 1; j <= rows; j++) {
if (j == 1 || j == rows) {
printf("*");
} else {
printf(" "); // Print space for inner columns
}
}
printf("\n"); // Move to the next line
}
Complete Example Code:
C
#include <stdio.h>
int main() {
int rows, i, j;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; i++) {
for (j = 1; j <= rows; j++) {
if (j == 1 || j == rows || i == 1 || i == rows) {
printf("*"); // Print stars for borders
} else {
printf(" "); // Print spaces for hollowness
}
}
printf("\n"); // Move to the next line
}
return 0;
}
Explanation
- The outer
for
loop iterates through each row of the pattern. - The inner
for
loop iterates through each column within a row. - The
if
condition checks if the current position is on the border of the square (first or last column, or first or last row). - If it’s on the border, a star (
*
) is printed; otherwise, a space is printed to create the hollow effect. printf("\n")
moves the cursor to the next line after printing each row.
Key Points to Remember
- The nested loops control the positioning of stars and spaces.
- The
if
condition determines whether to print a star or a space based on the coordinates. - Adjust the
rows
variable to control the size of the hollow square pattern.