Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Program to print Square inside a Square in C
In C, printing a square inside a square involves creating a pattern where two square borders are drawn using nested loops. The outer square forms the boundary, while an inner square is positioned within it, creating a nested square pattern.
Syntax
for (row = 1; row <= size; row++) {
for (col = 1; col <= size; col++) {
// Logic to print outer or inner square borders
}
}
Algorithm
- Accept the number of rows for the outer square from the user
- Use nested loops to iterate through each position
- Print '#' for outer square borders (first/last row/column)
- Print '#' for inner square borders based on calculated positions
- Print spaces for all other positions
Example
This program creates a square inside a square pattern using '#' characters −
#include <stdio.h>
int main() {
int r, c, rows;
printf("Enter the Number of rows to draw Square inside a Square: ");
scanf("%d", &rows);
printf("
");
for (r = 1; r <= rows; r++) {
for (c = 1; c <= rows; c++) {
if ((r == 1 || r == rows || c == 1 || c == rows) ||
(r >= 3 && r <= rows - 2 && c >= 3 && c <= rows - 2) &&
(r == 3 || r == rows - 2 || c == 3 || c == rows - 2)) {
printf("#");
} else {
printf(" ");
}
}
printf("
");
}
return 0;
}
Enter the Number of rows to draw Square inside a Square: 8 ######## # # # #### # # # # # # # # # # #### # # # ########
How It Works
The pattern logic uses two conditions:
-
Outer square: Print '#' when
r == 1orr == rowsorc == 1orc == rows - Inner square: Print '#' when position is on the inner square border (row 3, row rows-2, column 3, or column rows-2)
- Empty space: Print space for all other positions
Key Points
- The inner square starts at position (3,3) and ends at (rows-2, rows-2)
- Minimum size should be 5x5 to clearly show both squares
- The pattern works best with odd-numbered dimensions
Conclusion
This program demonstrates nested loop control and conditional logic to create geometric patterns. The square-in-square pattern is useful for understanding coordinate-based printing in C programming.
Advertisements
