Print Hollow Square Star Pattern

PRINTING PATTERN:

****

*    *

*    *

****

PREREQUISITE:

Basic knowledge of C language and use of loops.

ALGORITHM:

  1. Take number of rows/columns as input from the user (length of side of square) and store it in any variable (‘l’ in this case).
  2. Run  a loop ‘l’ number of times to iterate through all the rows. From i=0 to i<l. The loop should be structured as for( i=0; i<l ; i++).
  3. Run a nested loop inside the main loop for printing stars . From j=0 to j<l. The loop should be structured as for( j=0 ; j<l : j++).
  4. Inside the above loop print stars only if  i=0 or i=l-1 or j=0 or j=l-1 in all other cases print a blank space.
  5. Move to the next line by printing a new line. printf(“\n”).

Code in C:

#include<stdio.h>
int main()
{
int i,j,l;    //declaring integers i,j for loops and l for the number of rows
printf(" Enter the number of rows\n");   //Asking user for input
scanf("%d",&l);   //taking input for number of rows and saving in variable l
for(i=0;i<l;i++) //Outer loop for number of rows
   {
      for(j=0;j<l;j++) //Inner loop for printing stars in each column of a row
         {
            if(i==0 || i==l-1 || j==0 || j==l-1) // condition for printing stars
               {
                  printf("*");   // printing stars
               }
            else                 // else condition to print spaces 
               {
                  printf(" ");   //printing spaces
               }
         }
      printf("\n");       //Printing a new line after a row has been printed
   }
}

TAKING INPUT:
DISPLAYING OUTPUT:

33 comments on “Print Hollow Square Star Pattern”


  • rohini

    code in c++
    #include
    using namespace std;
    int main(){
    int row,col;
    cin>>row>>col;
    for(int i=1;i<=row;i++){
    for(int j=1;j<=col;j++){
    if(i==1||i==row){
    cout<<"*";
    }else if(j==1||j==col){
    cout<<"*";
    }else{
    cout<<" ";
    }

    }

    cout<<endl;
    }
    return 0;
    }


  • Nikita

    for i in range (n):
    str=””
    str+=” “*i
    for j in range(n):

    str+=”*”

    print()

    print(str,end=” “)


  • yaswanth

    n=4
    for i in range (n):
    for j in range(n):
    if i==0 or i==n-1 or j==0 or j==n-1:
    print(“*”,end=” “)
    else:
    print(” “,end=” “)
    print()


  • 19-577

    n=int(input())
    t=2
    for i in range(1,n+1):
    if i==1 or i==n:
    print(“*”*n)
    else:
    l=”*”+” “*(n-t)+”*”
    print(l)


  • tiwarishani461

    “” Hollo Square in C++ ”
    #include
    using namespace std;
    int main() {
    int rows, i, j;
    cout << "Enter the number of rows: " <> rows;

    for (i = 0; i < rows; i++) {
    for (j = 0; j < rows; j++) {
    if (i == 0 || i == rows-1 || j == 0 || j == rows-1) {
    cout << "*";
    } else {
    cout << " ";
    }
    }
    cout << endl;
    }

    return 0;
    }