Pattern to print X in a rectangular box
Last Updated :
20 Feb, 2023
Given the value of length, print the X pattern in a box using # and ” “
Examples:
Input : 10
Output : ##########
## ##
# # # #
# # # #
# ## #
# ## #
# # # #
# # # #
## ##
##########
Input : 7
Output : #######
## ##
# # # #
# # #
# # # #
## ##
#######
Below is the implementation to print X in a rectangular box pattern:
C++
#include <bits/stdc++.h>
using namespace std;
void pattern( int n)
{
for ( int i = 0; i < n; i++) {
for ( int j = 0; j < n; j++) {
if (i == 0 || i == n - 1 ||
j == 0 || j == n - 1 ||
i == j || i == n - 1 - j)
cout << "#" ;
else
cout << " " ;
}
cout << endl;
}
}
int main()
{
int n = 9;
pattern(n);
return 0;
}
|
Java
import java.io.*;
public class GFG {
static void pattern( int n)
{
for ( int i = 0 ; i < n; i++)
{
for ( int j = 0 ; j < n; j++)
{
if (i == 0 || i == n - 1 ||
j == 0 || j == n - 1 ||
i == j || i == n - 1 - j)
System.out.print( "#" );
else
System.out.print( " " );
}
System.out.println();
}
}
public static void main(String args[])
{
int n = 9 ;
pattern(n);;
}
}
|
Python 3
def pattern(n):
for i in range ( 0 , n):
for j in range ( 0 , n):
if (i = = 0 or i = = n - 1
or j = = 0 or j = = n - 1
or i = = j or i = = n - 1 - j):
print ( "#" , end = "")
else :
print ( " " ,end = "")
print ("")
n = 9
pattern(n)
|
C#
using System;
public class GFG {
static void pattern( int n)
{
for ( int i = 0; i < n; i++) {
for ( int j = 0; j < n; j++) {
if (i == 0 || i == n - 1 ||
j == 0 || j == n - 1 ||
i == j || i == n - 1 - j)
Console.Write( "#" );
else
Console.Write( " " );
}
Console.WriteLine();
}
}
public static void Main()
{
int n = 9;
pattern(n);
}
}
|
PHP
<?php
function pattern( $n )
{
for ( $i = 0; $i < $n ; $i ++) {
for ( $j = 0; $j < $n ; $j ++) {
if ( $i == 0 || $i == $n - 1 ||
$j == 0 || $j == $n - 1 ||
$i == $j || $i == $n - 1 - $j )
echo "#" ;
else
echo " " ;
}
echo "\n" ;
}
}
$n = 9;
pattern( $n );
?>
|
Javascript
<script>
function pattern(n) {
for ( var i = 0; i < n; i++) {
for ( var j = 0; j < n; j++) {
if (
i === 0 ||
i === n - 1 ||
j === 0 ||
j === n - 1 ||
i === j ||
i === n - 1 - j
)
document.write( "#" );
else document.write( " " );
}
document.write( "<br>" );
}
}
var n = 9;
pattern(n);
</script>
|
Output:
#########
## ##
# # # #
# # # #
# # #
# # # #
# # # #
## ##
#########
Time complexity: O(n^2) for given n
Auxiliary space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...