# Find the Pattern of 1’s inside 0’s using C++

In this article we are given values of several rows and several columns. We need to print a Box pattern such that 1’s get printed on 1st row, 1st column, last row, last column, and 0’s get printed on remaining elements. For example −

Input : rows = 5, columns = 4
Output :
1 1 1 1
1 0 0 1
1 0 0 1
1 0 0 1
1 1 1 1

Input : rows = 8, columns = 9
Output :
1 1 1 1 1 1 1 1 1
1 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 1
1 1 1 1 1 1 1 1 1

## Approach to find The Solution

One simple approach can be iterating every row and column and checking if the element lies in the first row, first column, last row, and last column; if yes, print ‘1’; otherwise, we are inside the border print ‘0’.In this way, we can form a box pattern the way we wanted.

## Example

using namespace std;

#include <bits/stdc++.h>
// Function to print pattern
void create_pattern (int rows, int columns) {

int i, j;
for (i = 1; i <= rows; i++) {
for (j = 1; j <= columns; j++) {
// If element is in first/last row or first/last column
if (i == 1 || i == rows || j == 1 || j == columns) {
cout << " 1";
} else {
cout << " 0";
}
}
cout << "\n";
}
return;
}

int main () {
int no_of_rows = 7;
int no_of_columns = 8;

create_pattern (no_of_rows, no_of_columns);
return 0;
}

## Output

1 1 1 1 1 1 1 1
1 0 0 0 0 0 0 1
1 0 0 0 0 0 0 1
1 0 0 0 0 0 0 1
1 0 0 0 0 0 0 1
1 0 0 0 0 0 0 1
1 1 1 1 1 1 1 1

## Explanation of the above code

• Calling create_pattern() function with values of number of rows and number of columns
• Outer loop for (i = 1; i <= rows; i++) to iterate from 1 to rows to go through rows.
• Inner loop for (j = 1; j <= columns; j++) to iterate through 1 to columns to go through columns.
• Checking if (i == 1 || i == rows || j == 1 || j == columns) element is in the first/last row or first/last column printing ‘1’ for yes and ‘0’ for no.

## Conclusion

In this article, we solve printing box patterns from the number of rows and columns given, i.e., the pattern of 1’s inside 0’s. We also created a C++ program to solve this problem. We can create the same program from various other languages like C, java, python, etc. Hope you find this Article helpful.

Advertisements