Home  >  Article  >  Backend Development  >  Find patterns of 1 in 0 using C++

Find patterns of 1 in 0 using C++

WBOY
WBOYforward
2023-09-07 23:29:02943browse

Find patterns of 1 in 0 using C++

In this article, we have given the values ​​for several rows and columns. We need to print a box pattern such that 1 is printed on the first row, first column, last row, and last column, and 0 is printed on the 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

Ways to find the solution

A simple way is to iterate over each row and column, checking if the element is in the first row, first column, last row and last column ;If yes, we print "1"; otherwise, we print "0" within the bounds. This way we can form the box pattern we want.

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

  • Call the create_pattern() function with the values ​​of row and column number
  • The outer loop (i = 1; i
  • The inner loop (j = 1; j
  • Check if (i == 1 || i == rows || j == 1 || j == columns), whether the element is in the first row/last row or first column/last column, If so, print '1', otherwise print '0'.

Conclusion

In this article, we solved the problem of printing a box pattern based on the given number of rows and columns, i.e. a pattern that prints 1 out of 0. We also created a C program to solve this problem. We can create the same program using various other languages ​​like C, Java, Python, etc. Hope you found this article helpful.

The above is the detailed content of Find patterns of 1 in 0 using C++. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete