Printing Hollow pattern in CPP

By | May 5, 2023

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:

  1. To iterate through rows, run an outer loop from 1 to rows. Define a loop with structure for(i=1; i<=rows; i++)
  2. To iterate through columns, run an inner loop from 1 to columns. Define loop with structure for(j=1; j<=columns; j++)
  3. 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.
  4. 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)

Author: Mithlesh Upadhyay

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.