Introduction
A hollow square star pattern consists of stars (*
) forming the boundary of the square, with the inner part being hollow (filled with spaces). This exercise helps beginners practice how to control loops and conditionally print characters to form patterns in C programming.
Problem Statement
Create a C program that:
- Accepts the number of rows and columns for the square.
- Prints a hollow square star pattern.
Example:
- Input:
rows = 5
- Output:
***** * * * * * * *****
Solution Steps
- Input the Number of Rows: The size determines the number of rows and columns for the square.
- Use Nested Loops: The outer loop handles the rows, and the inner loop handles printing the stars and spaces.
- Conditionally Print Stars: Print stars on the boundary (first and last rows, first and last columns) and print spaces inside to create the hollow effect.
C Program
#include <stdio.h>
int main() {
int i, j, rows;
// Step 1: Accept the number of rows (and columns) for the square
printf("Enter the number of rows (and columns): ");
scanf("%d", &rows);
// Step 2: Outer loop for rows
for (i = 1; i <= rows; i++) {
// Step 3: Inner loop for columns
for (j = 1; j <= rows; j++) {
// Step 4: Print stars at the boundary of the square
if (i == 1 || i == rows || j == 1 || j == rows) {
printf("*");
} else {
printf(" "); // Print space inside the square
}
}
// Move to the next line after each row
printf("\n");
}
return 0;
}
Explanation
Step 1: Input Number of Rows
- The program begins by asking the user to input the number of rows (and columns, since it’s a square) for the hollow square pattern.
Step 2: Outer Loop for Rows
- The outer loop controls how many rows are printed. It runs from
1
torows
.
Step 3: Inner Loop for Columns
- The inner loop controls how many columns are printed in each row, matching the number of rows.
Step 4: Conditional Printing
- Stars (
*
) are printed at the boundary positions: wheni == 1
,i == rows
,j == 1
, orj == rows
. Spaces are printed inside the square.
Output Example
For rows = 5
, the output will be:
*****
* *
* *
* *
*****
For rows = 6
, the output will be:
******
* *
* *
* *
* *
******
Conclusion
This C program prints a hollow square pattern using stars (*
) by printing stars at the boundary and spaces inside. It helps beginners understand how to control nested loops and use conditional statements to format output in C programming.
Comments
Post a Comment
Leave Comment