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

  1. Accept the number of rows for the outer square from the user
  2. Use nested loops to iterate through each position
  3. Print '#' for outer square borders (first/last row/column)
  4. Print '#' for inner square borders based on calculated positions
  5. 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 == 1 or r == rows or c == 1 or c == 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.

Updated on: 2026-03-15T12:38:05+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements