C++ 打印 1 和 0 行图案程序

使用 For 循环和示例编写 C++ 程序以打印 1 和 0 行图案。在此 C++ 示例中,我们在嵌套的 for 循环中使用 if-else 语句来检查奇偶行。如果行号为奇数,则打印 1,如果行号为偶数,则打印 0。

#include<iostream>
using namespace std;

int main()
{
	int i, j, rows, columns;
     
    cout << "\nPlease Enter the Number of Rows = ";
    cin >> rows;
    
    cout << "\nPlease Enter the Number of Columns = ";
    cin >> columns;
     
    cout << "\n---1 and 0 Number Pattern-----\n";
    for(i = 1; i <= rows; i++)
    {
    	for(j = 1; j <= columns; j++)
		{
			if(i % 2 != 0)
			{
				cout << "1";
			}
			else
			{
				cout << "0";
			}       	
        }
        cout << "\n";
    }
		
 	return 0;
}
C++ Program to Print 1 and 0 Row Pattern

使用 While 循环打印 1 和 0 行图案的 C++ 程序

#include<iostream>
using namespace std;

int main()
{
	int i, j, rows, columns;
     
    cout << "\nPlease Enter the Number of Rows = ";
    cin >> rows;
    
    cout << "\nPlease Enter the Number of Columns = ";
    cin >> columns;
     
    cout << "\n---1 and 0 Number Pattern-----\n";
    i = 1;
    while(i <= rows)
    {
    	j = 1; 
    	while(j <= columns)
		{
			if(i % 2 != 0)
			{
				cout << "1";
			}
			else
			{
				cout << "0";
			} 
			j++;      	
        }
        cout << "\n";
        i++;
    }
		
 	return 0;
}
Please Enter the Number of Rows = 6

Please Enter the Number of Columns = 15

---1 and 0 Number Pattern-----
111111111111111
000000000000000
111111111111111
000000000000000
111111111111111
000000000000000

在此 C++ 1 和 0 行图案示例中,我们在嵌套的 for 循环内直接打印 i% 2 的结果。

#include<iostream>
using namespace std;

int main()
{
	int i, j, rows, columns;
     
    cout << "\nPlease Enter the Number of Rows = ";
    cin >> rows;
    
    cout << "\nPlease Enter the Number of Columns = ";
    cin >> columns;
     
    cout << "\n---1 and 0 Number Pattern-----\n";
    for(i = 1; i <= rows; i++)
    {
    	for(j = 1; j <= columns; j++)
		{
			cout << i % 2;     	
        }
        cout << "\n";
    }
		
 	return 0;
}
Please Enter the Number of Rows = 8

Please Enter the Number of Columns = 20

---1 and 0 Number Pattern-----
11111111111111111111
00000000000000000000
11111111111111111111
00000000000000000000
11111111111111111111
00000000000000000000
11111111111111111111
00000000000000000000