Given the value of n, print a hollow square of side length n and inside it a solid square of side length (n – 4) using stars(*).
Examples :
Input : n = 6
Output :
******
* *
* ** *
* ** *
* *
******
Input : n = 11
Output :
***********
* *
* ******* *
* ******* *
* ******* *
* ******* *
* ******* *
* ******* *
* ******* *
* *
***********
C++
#include <bits/stdc++.h>
using namespace std;
void print_Pattern( int n)
{
for ( int i = 1; i <= n; i++) {
for ( int j = 1; j <= n; j++) {
if ((i == 1 || i == n) || (j == 1 || j == n) ||
(i >= 3 && i <= n - 2) && (j >= 3 && j <= n - 2))
cout<< "*" ;
else
cout<< " " ;
}
cout<<endl;
}
}
int main()
{
int n = 6;
print_Pattern(n);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static void print_Pattern( int n)
{
for ( int i = 1 ; i <= n; i++)
{
for ( int j = 1 ; j <= n; j++)
{
if ((i == 1 || i == n) || (j == 1 || j == n) ||
(i >= 3 && i <= n - 2 ) && (j >= 3 && j <= n - 2 ))
System.out.print( "*" );
else
System.out.print( " " );
}
System.out.println();
}
}
public static void main (String[] args)
{
int n = 6 ;
print_Pattern(n);
}
}
|
Python3
def print_Pattern(n):
for i in range ( 1 , n + 1 ):
for j in range ( 1 , n + 1 ):
if ((i = = 1 or i = = n) or
(j = = 1 or j = = n) or
(i > = 3 and i < = n - 2 ) and
(j > = 3 and j < = n - 2 )):
print ( "*" , end = "")
else :
print (end = " " )
print ()
n = 6
print_Pattern(n)
|
C#
using System;
class GFG {
static void print_Pattern( int n)
{
for ( int i = 1; i <= n; i++)
{
for ( int j = 1; j <= n; j++)
{
if ((i == 1 || i == n) ||
(j == 1 || j == n) ||
(i >= 3 && i <= n - 2) &&
(j >= 3 && j <= n - 2))
Console.Write( "*" );
else
Console.Write( " " );
}
Console.WriteLine();
}
}
public static void Main ()
{
int n = 6;
print_Pattern(n);
}
}
|
PHP
<?php
function print_Pattern( $n )
{
for ( $i = 1; $i <= $n ; $i ++)
{
for ( $j = 1; $j <= $n ; $j ++)
{
if (( $i == 1 || $i == $n ) ||
( $j == 1 || $j == $n ) ||
( $i >= 3 && $i <= $n - 2) &&
( $j >= 3 && $j <= $n - 2))
echo "*" ;
else
echo " " ;
}
echo "\n" ;
}
}
$n = 6;
print_Pattern( $n );
?>
|
Javascript
<script>
function print_Pattern(n)
{
for ( var i = 1; i <= n; i++)
{
for ( var j = 1; j <= n; j++)
{
if (
i == 1 ||
i == n ||
j == 1 ||
j == n ||
(i >= 3 && i <= n - 2 && j >= 3 && j <= n - 2)
)
document.write( "*" );
else document.write( " " );
}
document.write( "<br>" );
}
}
var n = 6;
print_Pattern(n);
</script>
|
Output :
******
* *
* ** *
* ** *
* *
******
Time complexity: O(n2) for given input n
Auxiliary Space: O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
20 Feb, 2023
Like Article
Save Article