Introduction
A square star pattern is a simple arrangement of stars (*
) printed in a square shape. This is a common beginner exercise in C programming to help practice using loops to control output.
Problem Statement
Create a C program that:
- Accepts the number of rows (and columns, since it's a square).
- Prints a square pattern using stars (
*
).
Example:
- Input:
rows = 5
- Output:
***** ***** ***** ***** *****
Solution Steps
- Input the Number of Rows: The size determines the number of rows and columns (since it's a square).
- Use Nested Loops: The outer loop handles the rows, and the inner loop handles the columns by printing stars.
- Display the Square Pattern: Print a square with the same number of stars in each row and column.
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 to print stars in each row
for (j = 1; j <= rows; j++) {
printf("*");
}
// Move to the next line after each row
printf("\n");
}
return 0;
}
Explanation
Step 1: Input Number of Rows
- The program starts by asking the user for the number of rows (and columns, since it's a square pattern).
Step 2: Outer Loop for Rows
- The outer loop runs from 1 to
rows
, controlling how many rows to print.
Step 3: Inner Loop for Columns
- The inner loop prints the stars (
*
) for each row. Since it is a square, the number of stars in each row equals the number of rows.
Output Example
For rows = 5
, the output will be:
*****
*****
*****
*****
*****
For rows = 3
, the output will be:
***
***
***
Conclusion
This C program prints a simple square pattern using stars (*
). The program uses nested loops to print the stars in both rows and columns. This is a useful exercise to practice loop control in C programming.
Comments
Post a Comment
Leave Comment