I'm a newbie in C++ and I'm supposed to write a program for a pattern generator that prints 2 different characters with different frequencies (input by user). The number of rows and columns are also determined by user.
For example, ‘*’ must be repeated three times and ‘+’ twice in 4 rows of 21 column, the pattern should look like this:
***++***++***++***++*
**++***++***++***++**
*++***++***++***++***
++***++***++***++***+
However my output is giving me 21 columns and 20 rows which I think makes the 'rows' variable in my code below useless, but I'm not sure why this is happening.
My output:
***++***++***++***++*
**++***++***++***++**
*++***++***++***++***
++***++***++***++***+
+***++***++***++***++
***++***++***++***++*
**++***++***++***++**
*++***++***++***++***
++***++***++***++***+
+***++***++***++***++
***++***++***++***++*
**++***++***++***++**
*++***++***++***++***
++***++***++***++***+
+***++***++***++***++
***++***++***++***++*
**++***++***++***++**
*++***++***++***++***
++***++***++***++***+
+***++***++***++***++
#include <iostream>
using namespace std;
int main()
{
char a, b;
int n, // number of times char a is repeated
m, // number of times char b is repeated
rows, // number of rows
columns, // number of columns
sumCharInRow = 0;
cout << "Please input your first character: ";
cin >> a;
cout << "How many times should this character be repeated?: ";
cin >> n;
cout << "Please input your second character: ";
cin >> b;
cout << "How many times should this character be repeated?: ";
cin >> m;
cout << "Please input the number of rows: ";
cin >> rows;
cout << "Please input the number of columns: ";
cin >> columns;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
for (int k = 0; k < n; k++) {
cout << a;
sumCharInRow++;
if (sumCharInRow >= columns) {
cout << "\n";
sumCharInRow = 0;
}
}
for (int l = 0; l < m; l++) {
cout << b;
sumCharInRow++;
if (sumCharInRow >= columns) {
cout << "\n";
sumCharInRow = 0;
}
}
}
}
return 0;
}
Can I know why it's not giving the expected output because I'm stumped. And also I'd really love to see what are the better alternatives to write this program. Thank you very much in advance!
Edit: I understand that "using namespace std" is borderline a crime in C++ but for the sake of readability of this simple program, my lecturer insists that we use this.
Aucun commentaire:
Enregistrer un commentaire