So i'm working on this task, where i have to find a specific column or row given to me by the user. But it works fine till i end up trying to display the second or third row, in which case it prints out all the rows not only the one i specify.
int A[3][3];
class Matrix {
public:
int value;
int row;
int col;
string answer;
void printArray();
void showRow(int a);
void showCol(int c);
};
int main()
{
Matrix m;
while (true)
{
cout << "Would you like to see a row or a column?(r/c) : " << endl;
cin >> m.answer;
if (m.answer == "r") {
cout << "Which row would you like to see ?" << endl;
int chosenRow;
cin >> chosenRow;
cout << endl;
m.showRow(chosenRow);
}
}
return 0;
}
void Matrix::printArray() {
for (int i = 0; i < 3; i++) {
for (int y = 0; y < 3; y++) {
cout << A[i][y] << " ";
}
cout << endl;
}
}
void Matrix::showRow(int a) {
for (int j = 0; j <= a; j++) {
for (int b = 0; b < 3; b++)
cout << A[j][b] << endl;
}
}
void Matrix::showCol(int c) {
for (int g = 0; g <= c; g++) {
for (int h = 0; h < 3; h++) {
cout << A[h][g] << endl;
}
}
}
I understand it might be a bit messy , and im kinda new to C++ and trying to figure stuff out.
I'm trying not to use pointers or adresses and keep it simple as possible. The printArray function works fine.
But as i mentioned, the showRow and the showCol, work fine if i only want to display the first column or row.. if i want to display the second or third it shows all previous rows or columns.
I also have a code where the user inputs the specific values for the row/column but i cut it out as its too long and bunch of none important code to this question. So just by default, there are some values for each position of a row or a column in the array.
@freesocks,
You are trying to use nested loops because that is what you used for a whole matrix, when you were having to loop through BOTH rows and columns.
But if you want a SPECIFIC row, for example, then you DON'T want to loop over rows, you just want to keep that specific row.
Consider your code here:
1 2 3 4 5 6
void Matrix::showRow(int a) {
for (int j = 0; j <= a; j++) {
for (int b = 0; b < 3; b++)
cout << A[j][b] << endl;
}
}
Here, you are telling it to loop over rows j=0,...,a but you only need row j=a.
In fact, you don't need the variable j at all, as it is always equal to a.
So remove the outer loop:
1 2 3 4
void Matrix::showRow(int a) {
for (int b = 0; b < 3; b++)
cout << A[a][b] << endl;
}
See if you can do the same with a particular column.