Given N = no of rows and M = no of columns, print the hollow pattern.
********** * * * * * * **********
Given above is an example of hollow pattern of 5 x 10.
Given below is the approach to built hollow pattern:
- To iterate through rows, run an outer loop from 1 to rows. Define a loop with structure for(i=1; i<=rows; i++)
- To iterate through columns, run an inner loop from 1 to columns. Define loop with structure for(j=1; j<=columns; j++)
- Inside this loop print star for first or last row or for first or last column, otherwise print blank space. Which is if(i==1 || i==rows || j==1 || j==columns) then print star otherwise space.
- After printing all columns of a row, move to next line i.e. print new line after inner loop.
#include <bits/stdc++.h >
using namespace std;
// function to pritn hollow pattern
void print(int rows, int columns)
{
int i, j; /*Iterate over each row */
for (i = 1; i <= rows; i++)
{
/*Iterate over each column */
for (j = 1; j <= columns; j++)
{
if (i == 1 || i == rows || j == 1 || j == columns)
{ /*Print star for 1st and last row, column */
cout << ("*");
}
else
{
cout << (" ");
}
} /*Move to the next line */
cout << ("\n");
}
}
// driver program to test the above function
int main()
{
int n = 5, m = 10;
print(n, m); // calls function to print hollow pattern return 0;
}
Output:
********** * * * * * * **********
Time complexity : O(n* m)
