In this article, I will show you, How to write a C program to print hollow square star pattern with diagonal. Here, one thing is important to know that all sides of the square must be the same.
Method1:
#include <stdio.h> int main() { int x = 0,y = 0; unsigned int squareSide = 0; printf("Enter Side of a Square = "); scanf("%u",&squareSide); for(x=1; x<=squareSide; ++x) { for(y=1; y<=squareSide; ++y) { // Checking boundary conditions and main // diagonal and secondary diagonal conditions if((x==1) || (x==squareSide) || (y==1) || (y==squareSide) || (x==y)|| (y==(squareSide - x + 1))) { //Print star printf("*"); } else { //Print space printf(" "); } } // Print new line printf("\n"); } return 0; }
Output1:
Method2:
#include <stdio.h> #define isBoundary(x,y,n) ((x==1) || (x==n) || (y==1) || (y==n) || (x==y)|| (y==(n - x + 1))) int main() { int x = 0,y = 0; unsigned int squareSide = 0; printf("Enter Side of a Square = "); scanf("%u",&squareSide); for(x=1; x<=squareSide; ++x) { for(y=1; y<=squareSide; ++y) { isBoundary(x,y,squareSide)? printf("*"):printf(" "); } // Print new line printf("\n"); } return 0; }
Output2: