Print a Square Star Pattern in C
To print a square star pattern in C, we use nested loops: an outer loop to handle the rows and an inner loop to print the stars in each row. This ensures that we get a perfect square shape, with each row containing the same number of stars as the number of rows.
Examples to Print a Square Star Pattern
1. Print a Simple Square Star Pattern
In this example, we will print a square star pattern of a fixed size (5×5). We will use nested loops, where the outer loop controls the number of rows and the inner loop prints stars in each row.
main.c
#include <stdio.h>
int main() {
int size = 5; // Define the size of the square
for (int i = 0; i < size; i++) { // Loop for rows
for (int j = 0; j < size; j++) { // Loop for columns
printf("* ");
}
printf("\n"); // Move to the next line
}
return 0;
}
Explanation:
- We declare an integer variable
size
and set it to 5, which defines the size of the square. - The outer loop (
for (int i = 0; i < size; i++)
) runs 5 times, creating 5 rows. - The inner loop (
for (int j = 0; j < size; j++)
) runs 5 times per row, printing 5 stars. - The
printf("\n")
moves the cursor to the next line after printing a full row.
Output:
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
2. Print a Square Star Pattern with User Input
In this example, we will modify the program to take the size of the square as user input. This allows the user to print a square of any desired dimension.
main.c
#include <stdio.h>
int main() {
int size;
printf("Enter the size of the square: ");
scanf("%d", &size); // Take input from user
for (int i = 0; i < size; i++) { // Loop for rows
for (int j = 0; j < size; j++) { // Loop for columns
printf("* ");
}
printf("\n"); // Move to the next line
}
return 0;
}
Explanation:
- We declare an integer variable
size
to store the user’s input. - The
scanf("%d", &size)
function takes the size from the user. - The nested loops work the same way as before, using the inputted size for both rows and columns.
- The program prints a square of the given size.
Output:
Enter the size of the square:
Enter an integer value. Let us enter 3.
Enter the size of the square: 3
* * *
* * *
* * *
Conclusion
In this tutorial, we covered different ways to print a square star pattern in C:
- Fixed Size Square Pattern: Using nested loops to print a predefined 5×5 square.
- Dynamic Size Square Pattern: Taking user input to print a square of any size.
The key concept is using for
loops, where the outer loop handles the rows, and the inner loop prints the stars in each row.