I received this assignment and I spent the last hour trying to figure it out but I don't seem to know how to do it. I have tried many ideas but none of them worked. Here is the expected output:
This is my final version of the code. It works however for some reason it doubles the number of columns. I'm not sure how to fix it.
int rows;
int columns;
int k = 0;
int j;
int i;
string pattern1;
string pattern2;
cout << "Enter number of desired rows: ";
cin >> rows;
cout << "Enter number of desired columns: ";
cin >> columns;
pattern1 = " \\@/";
pattern2 = " /*\\";
for (i = 1; i <= rows; i )
{
for (j = 1; j <= columns; j )
{
if (i % 2 == 0)
{
cout << " /@\\";
}
else
cout << pattern1;
if (k == 0)
{
if (i % 2 == 0)
{
cout << " \\*/";
}
else
cout << pattern2;
}
} cout << endl;
}
CodePudding user response:
I found the solution. Before, for each iteration of j it added two columns because the if statement was executed anyways because k is always 0. Now, I added a j at the end of the if statement so that whenever the compiler reads the if statement, it counts it as another iteration of the loop (what I mean is, we essentially make it that it adds two columns for every one iteration of the column (j) loop). But then I had to make the loop stop if j is actually equal to columns, thus I replaced the k==0 with j!=column. Here is the correct code.
#include <iostream>
using namespace std;
int main()
{
int rows;
int columns;
int k = 0;
int j;
int i;
string pattern1;
string pattern2;
cout << "Enter number of desired rows: ";
cin >> rows;
cout << "Enter number of desired columns: ";
cin >> columns;
int nc = (columns/2);
int nr = rows/2;
pattern1 = " \\@/";
pattern2 = " /*\\";
for (i = 1; i <= rows; i )
{
for (j = 1; j <= columns; j )
{
if (i % 2 == 0)
{
cout << " /@\\";
}
else
cout << pattern1;
if (columns!=j)
{
if (i % 2 == 0)
{
cout << " \\*/";
}
else
cout << pattern2;
j ;
}
} cout << endl;
}
}
CodePudding user response:
Here's a way:
- Two for loops, one for the rows and one for the columns.
- A 2x2 matrix with the 2 patterns (even column, odd column) for the even rows and the 2 patterns for the odd rows.
- For every row and column,
patterns[i % 2][j % 2]
will give you the even or odd pattern for the even or odd row. - You can print a space after each pattern except for the last column.
#include <iostream> // cout
#include <string_view>
#include <vector>
void print_pattern(size_t nrows, size_t ncols)
{
std::string_view patterns[2][2]{
{ R"(\@/)", R"(/*\)" },
{ R"(/@\)", R"(\*/)" },
};
for (size_t i{0}; i < nrows; i)
{
for (size_t j{0}; j < ncols; j)
{
std::cout << patterns[i % 2][j % 2] << ((j < ncols - 1) ? " " : "");
}
std::cout << "\n";
}
}
int main()
{
print_pattern(4, 5);
}