Program to print a rectangle pattern
Last Updated :
24 Feb, 2023
Given height h and width w, print a rectangular pattern as shown in the example below.
Examples:
Input : h = 4, w = 5
Output : @@@@@
@ @
@ @
@@@@@
Input : h = 7, w = 9
Output : @@@@@@@@
@ @
@ @
@ @
@ @
@ @
@@@@@@@@
The idea is to run two loops. One for the number of rows to be printed and the other for the number of columns. Print a ‘@’ only when the current row is first or last. OR the current column is first or last.
C++
#include<iostream>
using namespace std;
void printRectangle( int h, int w)
{
for ( int i=0; i<h; i++)
{
cout << "\n" ;
for ( int j=0; j<w; j++)
{
if (i == 0 || i == h-1 ||
j== 0 || j == w-1)
cout << "@" ;
else
cout << " " ;
}
}
}
int main()
{
int h = 4, w = 5;
printRectangle(h, w);
return 0;
}
|
Java
class GFG {
static void printRectangle( int h, int w)
{
for ( int i = 0 ; i < h; i++)
{
System.out.println();
for ( int j = 0 ; j < w; j++)
{
if (i == 0 || i == h- 1 ||
j== 0 || j == w- 1 )
System.out.print( "@" );
else
System.out.print( " " );
}
}
}
public static void main(String args[])
{
int h = 4 , w = 5 ;
printRectangle(h, w) ;
}
}
|
Python3
def printRectangle(h, w) :
for i in range ( 0 , h) :
print ("")
for j in range ( 0 , w) :
if (i = = 0 or i = = h - 1 or j = = 0 or j = = w - 1 ) :
print ( "@" ,end = "")
else :
print ( " " ,end = "")
h = 4
w = 5
printRectangle(h, w)
|
PHP
<?php
function printRectangle( $h , $w )
{
for ( $i = 0; $i < $h ; $i ++)
{
echo "\n" ;
for ( $j = 0; $j < $w ; $j ++)
{
if ( $i == 0 || $i == $h - 1 ||
$j == 0 || $j == $w - 1)
echo "@" ;
else
echo " " ;
}
}
}
$h = 4;
$w = 5;
printRectangle( $h , $w );
?>
|
Javascript
function printRectangle(h, w)
{
for ( var i=0; i<h; i++)
{
console.log( "\n" );
for ( var j=0; j<w; j++)
{
if (i == 0 || i == h-1 ||
j== 0 || j == w-1)
console.log( "@" );
else
console.log( " " );
}
}
}
var h = 4, w = 5;
printRectangle(h, w);
<script>
|
C#
using System;
public class GFG
{
static void PrintRectangle( int h, int w)
{
for ( int i = 0; i < h; i++)
{
Console.WriteLine();
for ( int j = 0; j < w; j++)
{
if (i == 0 || i == h - 1 ||
j == 0 || j == w - 1)
Console.Write( "@" );
else
Console.Write( " " );
}
}
}
public static void Main( string [] args)
{
int h = 4, w = 5;
PrintRectangle(h, w);
}
}
|
Output
@@@@@
@ @
@ @
@@@@@
Time complexity: O(n2), Space Complexity: O(1) // Constant space.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...