Given two integers n and m, print a hollow rectangle star pattern of the given n rows and m columns. In this pattern, stars (*) are printed on the boundary of the rectangle, while the inner area contains spaces.
Example:
Input: n = 6, m = 20
Output:Hollow Rectangle
Try It Yourself
Using Nested Loops – O(n*m) Time and O(1) Space
The pattern can be printed using two nested loops. The outer loop iterates through the rows, and the inner loop iterates through the columns. A star (*) is printed when the current position is on the first row, last row, first column, or last column; otherwise, a space is printed.
#include <iostream>
using namespace std;
void printHollowRect(int n, int m)
{
int i, j;
for (i = 1; i <= n; i++)
{
for (j = 1; j <= m; j++)
{
if (i == 1 || i == n ||
j == 1 || j == m)
cout << "*";
else
cout << " ";
}
cout << endl;
}
}
int main() {
int n = 6, m = 20;
printHollowRect(n, m);
return 0;
}
#include <stdio.h>
void printHollowRect(int n, int m)
{
int i, j;
for (i = 1; i <= n; i++)
{
for (j = 1; j <= m; j++)
{
if (i == 1 || i == n ||
j == 1 || j == m)
printf("*");
else
printf(" ");
}
printf("\n");
}
}
int main() {
int n = 6, m = 20;
printHollowRect(n, m);
return 0;
}
class GFG {
public static void printHollowRect(int n, int m) {
int i, j;
for (i = 1; i <= n; i++) {
for (j = 1; j <= m; j++) {
if (i == 1 || i == n || j == 1 || j == m)
System.out.print("*");
else
System.out.print(" ");
}
System.out.println();
}
}
public static void main(String[] args) {
int n = 6, m = 20;
printHollowRect(n, m);
}
}
def printHollowRect(n, m):
i = 1
while i <= n:
j = 1
while j <= m:
if i == 1 or i == n or j == 1 or j == m:
print("*", end="")
else:
print(" ", end="")
j += 1
print()
i += 1
if __name__ == '__main__':
n = 6
m = 20
printHollowRect(n, m)
using System;
class GFG {
static void printHollowRect(int n, int m) {
int i, j;
for (i = 1; i <= n; i++)
{
for (j = 1; j <= m; j++)
{
if (i == 1 || i == n || j == 1 || j == m)
Console.Write("*");
else
Console.Write(" ");
}
Console.WriteLine();
}
}
public static void Main()
{
int n = 6, m = 20;
printHollowRect(n, m);
}
}
function printHollowRect(n, m) {
let i, j;
for (i = 1; i <= n; i++) {
let line = "";
for (j = 1; j <= m; j++) {
if (i == 1 || i == n || j == 1 || j == m)
line += "*";
else
line += " ";
}
console.log(line);
}
}
// Driver code
const n = 6, m = 20;
printHollowRect(n, m);
