Program to print window pattern

Print the pattern in which there is a hollow square and plus sign inside it. Pattern will be as per the n i.e. number of rows given as shown in example. 

Examples: 

Input : 6
Output : * * * * * *
         *   * *   * 
         * * * * * * 
         * * * * * * 
         *   * *   * 
         * * * * * *

Input : 7
Output : * * * * * * * 
         *     *     * 
         *     *     * 
         * * * * * * * 
         *     *     * 
         *     *     * 
         * * * * * * *

Approach: 

  • We will start a for loop up till n and inside this also there is for loop up till n. 
  • In this simply we have to check if row is first or last or column is first or last, then print “*”. 
  • Now we have to check for the middle row and column. 
  • So when n is odd, we will have a middle row and column and if row or column is in middle then we will print “*”.
  • If n is even,then rows or columns if equal to these values n/2 and (n/2)+1, then we will print “*”. 
  • Else everywhere we have to print ” “(space).

Below is the implementation.
 

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to print the pattern 
# hollow square with plus inside it
# window pattern
  
  
# function to print pattern n means 
# number of rows which we want
def window_pattern(n):
      
    # if n is odd then we will have
    # only one middle element
    if n % 2 != 0:
        c = ( n // 2 ) + 1
        d = 0
          
    # if n is even then we will have two
    # values
    else:
        c = ( n // 2 ) + 1
        d = ( n // 2 )
  
    for i in range( 1 , n + 1 ):
        for j in range( 1 , n + 1 ):
              
            # if i,j equals to corner row or
            # column then "*"
            if i == 1 or j == 1 or i == n or j == n:
                print("*",end=" ")
                  
            else:
                  
                # if i,j equals to the middle row 
                # or column then  "*"
                if i == c or j == c:
                    print("*",end=" ")
                      
                elif i == d or j == d:
                    print("*",end=" ")
                  
                else:
                    print(" ",end=" ")
          
        print()
  
  
# Driver Code 
if __name__ == "__main__":
    n = 7
    window_pattern(n)

chevron_right


Output :

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

Time complexity: O(n^2)
 




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.