⓱C Program to Print a Square Pattern
- Get link
- X
- Other Apps
C Program to Print a Square Pattern
#include <stdio.h>
int main()
{
int i, j, n;
printf("Enter the size of square: ");
scanf("%d", &n);
for(i = 1; i <= n; i++) // Outer loop for rows
{
for(j = 1; j <= n; j++) // Inner loop for columns
{
printf("* ");
}
printf("\n"); // Move to next line after one row
}
return 0;
}
Explanation of Loops
1️⃣ Outer Loop (Row Loop)
for(i = 1; i <= n; i++)
Purpose: Controls the number of rows
Example if n = 5
| Iteration | Row Printed |
|---|---|
| i = 1 | First row |
| i = 2 | Second row |
| i = 3 | Third row |
| i = 4 | Fourth row |
| i = 5 | Fifth row |
So the outer loop runs n times.
2️⃣ Inner Loop (Column Loop)
for(j = 1; j <= n; j++)
Purpose: Prints stars in each row
For every row, the inner loop prints n stars.
Example for first row:
| j value | Output |
|---|---|
| j = 1 | * |
| j = 2 | * |
| j = 3 | * |
| j = 4 | * |
| j = 5 | * |
3️⃣ New Line
printf("\n");
After printing n stars, we move to the next row.
How the Program Works (Step-by-Step)
If n = 3
i = 1→ inner loop prints***i = 2→ inner loop prints***i = 3→ inner loop prints***
Output
* * *
* * *
* * *
Important Concept for Pattern Questions
👉 Outer loop → rows
👉 Inner loop → columns / printing symbols
This rule works for almost all pattern programs.
✅ Next Program: Printing a Right Triangle Star Pattern in C using loops
- Get link
- X
- Other Apps
Comments
Post a Comment