Last Updated: 6 Apr, 2022

Pattern Printing

Easy
Asked in companies
HashedInCapegemini Consulting India Private LimitedCatchpoint

Problem statement

Ninja has been given two integers 'M' and ‘N’.

Now Ninja has to draw a rectangle of height ‘M’ and breadth ‘N’ using the character * such that the * only occurs at the boundaries of the rectangle, and inside of this boundary, there is space only.

Now, Ninja doesn’t know how to perform this operation.

You being Ninja's best friend, your task is to help Ninja to solve this problem.

EXAMPLE:
Input: 'M' = 2, ‘N’ = 2  

Output: 
**
**
Input Format :
The first line will contain the integer 'T', denoting the number of test cases.

For each test case, one line contains two space-separated integers ‘M’ and ‘N’, where ‘M’ is the height of the rectangle and ‘N’ is the breadth of the rectangle.
Output format :
For each test case, print the pattern of height ‘M’ and breadth ‘N’
Constraints :
1 <= 'T' <= 10
1 <= 'M' <= 10^5
1 <= 'N' <= 10^5
1 <= 'M' * 'N' <= 10^5
Time Limit: 1 sec

Approaches

01 Approach

Approach: 

 

For each (‘I’, ‘J’) such that 1 <= ‘I’ <= ‘M’ and 1 <= ‘J’ <= ‘N’ we have to print either ‘*’ or ‘ ‘(space). So we have to iterate through all (‘I’, ‘J’) pairs and check that if ‘I’ or ‘J’ anyone present at the boundary that print ‘*’ else print ‘ ‘. That is if (‘I’ == 1 || ‘I’ == ’M’ || ‘J’ == 1 || ‘J’ == ’N’) means that this pair of 

('I', ‘J’) will come at the boundary.

 

Algorithm :  

 

  • Iterate for ‘I’ from 1 to ‘M’
  • For each ‘I’, iterate for ‘J’ from 1 to ‘N’
  • Iterate over the string ‘num’
    • If  (‘I’==1 || ‘I’==’M’ || ‘J’==1 || ‘J’==’N’)
      • print(‘*’).
    • Else
      • print(‘ ‘)