Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Print concentric rectangular pattern in a 2d matrix in C++
In this problem, we have to print a rectangular pattern in a 2D matrix in such a way that they are concentric to each other.
Let’s take an example to understand this problem better,
For n=4 is : 4 4 4 4 4 4 4 4 3 3 3 3 3 4 4 3 2 2 2 3 4 4 3 2 1 2 3 4 4 3 2 2 2 3 4 4 3 3 3 3 3 4 4 4 4 4 4 4 4
Here, we have to print the pattern as above taking n, integer value and print concentric rectangles as −
n n n n n n n-1 n-1 n-1 n n n-1 n-2 n-1 n n n-1 n-1 n-1 n n n n n n
Now, in this problem, as we can see there are (2n-1) columns and rows in the 2D matrix in total. This 2D matrix is printed in two parts. The upper one will be from 0 to (2n-1)/2 and the lower half will be from ((2n-1)/2+1) to 2n-2.
Now, each row will go on decreasing value by 1 until the number reaches the number of rows i.e. 1 to i (no. of rows). Then it increases the number back to n.
Example
Using this logic lets create a program to solve the problem,
#include <bits/stdc++.h>
using namespace std;
void print2Dsequence(int n){
int s = 2 * n - 1;
for (int i = 0; i < (s / 2) + 1; i++) {
int m = n;
for (int j = 0; j < i; j++) {
cout << m << " ";
m--;
}
for (int k = 0; k < s - 2 * i; k++) {
cout << n - i << " ";
}
m = n - i + 1;
for (int l = 0; l < i; l++) {
cout << m << " ";
m++;
}
cout << endl;
}
for (int i = s / 2 - 1; i >= 0; i--) {
int m = n;
for (int j = 0; j < i; j++) {
cout << m << " ";
m--;
}
for (int k = 0; k < s - 2 * i; k++) {
cout << n - i << " ";
}
m = n - i + 1;
for (int l = 0; l < i; l++) {
cout << m << " ";
m++;
}
cout << endl;
}
}
int main(){
int n = 4;
cout<<"The sequence of concurrent rectangle of 4 is : \n";
print2Dsequence(n);
return 0;
}
Output
The sequence of the concurrent rectangle of 4 is −
4 4 4 4 4 4 4 4 3 3 3 3 3 4 4 3 2 2 2 3 4 4 3 2 1 2 3 4 4 3 2 2 2 3 4 4 3 3 3 3 3 4 4 4 4 4 4 4 4