Home > Article > Backend Development > 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
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.
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; }
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
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!