hi, i'm starting out with c++ and have been writing a for-the-hell-of-it piece of code to calculate the product of two matrices. It runs but produced the wrong results. After hours of headaches I narrowed down the problem to the following code:
cout%26lt;%26lt;"enter the elements of matrix A from left to right, top to bottom %26gt;";
for (a=0; a%26lt;y1; a++)
{
for (b=0; b%26lt;x1; b++)
{
cin%26gt;%26gt;mat1[a][b];
}
}
where y1 and x1 are the height and width of matrix "mat1" respectively. The problem is that the numbers I enter get mixed up and the numbers that get put into the array are different.
example: If I declare the array mat1 to be of size x1=2 and y1=2, and input the numbers 1, 2, 3, 4 then when I display the array contents afterwards with cout, it turns out to be 1, 3, 3, 4.
If I enter the numbers 1,2,3,4,5,6,7,8,9 into a 3x3 array then it turns out to be 9 4 7
4 7 8
7 8 9
any help?
How to populate 2d array with user entered values in c++?
for some reason values diagonal to each other have the same values.
the code is correct i thnik
are you sure that the entire code is actually correct; it may not be this part that causing the wrong output. it could be the print function as well.
please include how you printed the values as well
good luck
Reply:I used java but and I always name my row and col that name
But I checked and it works.
int [] [] mat1 = new int [3][3];//java
for (int row=0; row %26lt; mat1.length; row++)
{
for (int col=0; col %26lt;mat1.length; col++)
{
cin%26gt;%26gt;mat1[row][col];
}
}
The print out was the same for loops
for (int row=0; row %26lt; 3; row++)
{
for (int col=0; col %26lt;3; col++)
System.out.println( mat1[row][col] +" ");//cout :-)
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment