编写一个 C++ 程序,使用 For 循环和示例打印 1 和 0 列图案。在此 C++ 列图案示例中,我们在嵌套的 for 循环中使用 if-else 语句来检查列号是偶数还是奇数。如果是奇数列,则打印 0,如果是偶数列,则打印 1。
#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 Column Pattern-----\n";
for(i = 1; i <= rows; i++)
{
for(j = 1; j <= columns; j++)
{
if(j % 2 != 0)
{
cout << "0";
}
else
{
cout << "1";
}
}
cout << "\n";
}
return 0;
}

使用 While 循环打印 0 和 1 列图案的 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 Column Pattern-----\n";
i = 1;
while(i <= rows)
{
j = 1;
while(j <= columns)
{
if(j % 2 != 0)
{
cout << "0";
}
else
{
cout << "1";
}
j++;
}
cout << "\n";
i++;
}
return 0;
}
Please Enter the Number of Rows = 8
Please Enter the Number of Columns = 13
---1 and 0 Column Pattern-----
0101010101010
0101010101010
0101010101010
0101010101010
0101010101010
0101010101010
0101010101010
0101010101010
在此 C++ 代码打印 1 和 0 列图案中,如果列是奇数列,则打印 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 Column Pattern-----\n";
for(i = 1; i <= rows; i++)
{
for(j = 1; j <= columns; j++)
{
if(j % 2 != 0)
{
cout << "1";
}
else
{
cout << "0";
}
}
cout << "\n";
}
return 0;
}
Please Enter the Number of Rows = 7
Please Enter the Number of Columns = 15
---1 and 0 Column Pattern-----
101010101010101
101010101010101
101010101010101
101010101010101
101010101010101
101010101010101
101010101010101
在此 C++ 1 和 0 列图案示例中,我们在嵌套的 for 循环内直接打印 j % 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 Column Pattern-----\n";
for(i = 1; i <= rows; i++)
{
for(j = 1; j <= columns; j++)
{
cout << j % 2;
}
cout << "\n";
}
return 0;
}
Please Enter the Number of Rows = 11
Please Enter the Number of Columns = 25
---1 and 0 Column Pattern-----
1010101010101010101010101
1010101010101010101010101
1010101010101010101010101
1010101010101010101010101
1010101010101010101010101
1010101010101010101010101
1010101010101010101010101
1010101010101010101010101
1010101010101010101010101
1010101010101010101010101
1010101010101010101010101