使用C++查詢0中1的模式
在本文中,我們給出了幾行和幾列的值。我們需要列印一個方框圖案,使得1列印在第一行、第一列、最後一行和最後一列,而0列印在其餘元素上。例如:
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
尋找解決方案的方法
一種簡單的方法是迭代每一行和每一列,並檢查元素是否位於第一行、第一列、最後一行和最後一列;如果是,則列印‘1’;否則,我們位於邊框內,則列印‘0’。透過這種方式,我們可以按照我們想要的方式形成一個方框圖案。
示例
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
以上程式碼的解釋
- 使用行數和列數的值呼叫create_pattern()函式。
- 外迴圈for (i = 1; i <= rows; i++) 迭代從1到rows,遍歷行。
- 內迴圈for (j = 1; j <= columns; j++) 迭代從1到columns,遍歷列。
- 檢查if (i == 1 || i == rows || j == 1 || j == columns) 元素是否在第一行/最後一行或第一列/最後一列,如果是則列印‘1’,否則列印‘0’。
結論
在本文中,我們解決了根據給定的行數和列數列印方框圖案的問題,即0中1的圖案。我們還建立了一個C++程式來解決這個問題。我們可以使用其他各種語言(如C、Java、Python等)建立相同的程式。希望本文對您有所幫助。
廣告