C program to print hollow square or rectangle star pattern

https://cdn.jsdelivr.net/gh/google/code-prettify@master/loader/run_prettify.js

Write a C program to print hollow square star(*) pattern series using for loop. How to print hollow square star pattern of N rows using for loop in C programming. Logic to print empty square star pattern in C program.

Logic to print hollow square star pattern

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

The above pattern is similar to square star pattern of N rows and N columns. Here star is printed only for first and last column or for first and last row.

Step by step descriptive logic to print empty square star pattern.

  1. Input number of rows to print from user. Store it in a variable say N.
  2. To iterate through rows, run an outer loop from 1 to N. For that define loop with structure for(i=1; i<=N; i++).
  3. To iterate through columns, run an inner loop from 1 to N. Define loop with structure for(j=1; j<=N; j++).
  4. Inside inner loop print star for first and last row or for first and last column. Which is print star if i==1 or i==N or j==1 or j==N, otherwise print space.
  5. After printing all columns of a row, move to next line i.e. print a blank line after inner loop.

Program to print hollow square pattern

/**
 * C program to print hollow square star pattern
 */

#include <stdio.h>

int main(){
	int i,j,n;
    /* Input number of rows from user */
	printf("Enter Number: \n");
	scanf("%d",&n);
    /* Iterate over each row */
	for(i=1;i<=n;i++)
	{
        /* Iterate over each column */
		for(j=1;j<=n;j++)
		{
		      if(i==1||i==n||j==1||j==n)
			printf("* "); // one Star and one space
			else
			printf("  "); //two spaces
		}	
	
	printf("\n");
	}
return 0;
}

Output

Happy Code Decoding šŸ˜‰ ….

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s