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 
// Function to print pattern
void create_pattern (int rows, int columns) {

   int i, j;
   for (i = 1; i 

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
  • Inner loop for (j = 1; j
  • 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.

Updated on: 2021-11-26T07:21:51+05:30

404 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements