How to print Hollow Square Pattern in C - Step by Step Examples



How to print Hollow Square Pattern in C ?

Answer

To print a Hollow Square Pattern in C, you can use nested loops. The outer loop controls the rows, and the inner loop controls the columns. Conditions are used to determine whether to print stars or spaces for the pattern.



✐ Examples

1 Print Hollow Square Pattern

In this example,

  1. We include the necessary header files for input/output functions.
  2. We define a function named printHollowSquare that takes the side length n as a parameter.
  3. We use two nested for loops, one for rows and one for columns, to iterate through each cell of the square.
  4. Within the loops, we use conditions to check if we are at the border or inside the square, printing stars (*) for the border and spaces ( ) for the inside.
  5. Finally, we call printHollowSquare with the desired side length to print the pattern.

C Program

#include <stdio.h>

void printHollowSquare(int n) {
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (i == 0 || i == n - 1 || j == 0 || j == n - 1) {
                printf("*");
            } else {
                printf(" ");
            }
        }
        printf("\n");
    }
}

int main() {
    int sideLength = 5;
    printHollowSquare(sideLength);
    return 0;
}

Output

*****
*   *
*   *
*   *
*****

Summary

In this tutorial, we learned How to print Hollow Square Pattern in C language with well detailed examples.




More C Pattern Printing Tutorials

  1. How to print Left Half Pyramid Pattern in C ?
  2. How to print Right Half Pyramid Pattern in C ?
  3. How to print Pyramid Pattern in C ?
  4. How to print Rhombus Pattern in C ?
  5. How to print Diamond Pattern in C ?
  6. How to print Hour Glass Pattern in C ?
  7. How to print Hollow Square Pattern in C ?
  8. How to print Hollow Pyramid Pattern in C ?
  9. How to print Hollow Inverted Pyramid Pattern in C ?
  10. How to print Hollow Diamond Pattern in C ?
  11. How to print Floyd's Trianlge Pattern in C ?
  12. How to print Pascal's Triangle Pattern in C ?