How to print following pattern in C :1st row->10101010...;2nd row->11001100..;3rd row ->11100011 and so on.
Number of alternate 0 and 1s depends on the row number.
Pattern should look like:
1010101010
1100110011
1110001110
Code:
#include<iostream>
using namespace std;
int main()
{
int row,col,cond;
cout <<"Enter the number of rows: ";
cin >> row;
cout <<"Enter the number of cols: ";
cin >> col;
int a[row][col]={0};
for(int i=0; i<row; i )
{
for(int j=0;j<col;j )
{
cond = (((j 1)/(i 1)) i 1);
// cout << "i=" << i <<"j="<<j<<"cond="<<cond <<endl;
if( (j <= i) )
{
a[i][j]=1;
if(cond j<col)
{
a[i][cond j]=1;
}
}
else if (a[i][j] !=1)
{
a[i][j]=0;
}
}
}
for(int i=0; i<row; i )
{
for(int j=0;j<col;j )
{
cout << a[i][j];
}
cout<<endl;
}
return 0;
}
Ouput:
Enter the number of rows: 4
Enter the number of cols: 9
101000000
111010000
111110100
111111101
CodePudding user response:
You are overcomplicating this - you don't need any arrays or tricky indexing.
Print one row at a time, starting with 1
.
Switch back and forth between 0
and 1
at the appropriate columns.
for (int r = 1; r <= row; r )
{
int symbol = 1;
for (int c = 1; c <= col; c )
{
std::cout << symbol;
if (c % r == 0)
{
symbol = 1 - symbol;
}
}
std::cout << std::endl;
}
CodePudding user response:
if you can use string ,you can create that and then slice it .
#include <iostream>
#include <string>
using namespace std;
std::string createStringChars(const char theChar, int repeatNo)
{
return std::string(repeatNo, theChar); //NRVO caller
}
std::string createAlignedString(int rows, int cols)
{
std::string result;
{
std::string temp;
for(int i = 0; i < rows; i)
{
temp.clear();
bool nextChar = false;
for(int j = 0; j < (cols / (i 1) 1); j)
{
if(nextChar)
temp = createStringChars('0', i 1);
else
temp = createStringChars('1', i 1);
nextChar = !nextChar;
}
result = (temp.substr(0, cols) "\n");
}
}
return result;
}
int main()
{
int row = 3, col = 10;
cout << "Enter the number of rows: ";
cin >> row;
cout << "Enter the number of cols: ";
cin >> col;
cout << "\n@@@@ result @@@@ \n" << createAlignedString(row, col) << endl;
return 0;
}