Reputation:
Currently I am working on an assignment that works with a 2D array. For a certain part of the assignment, I have to create a constructor that performs a variety of tasks detailed here:
(1) Finish the second constructor of Matrix class “Matrix(int r, int c, double v[][])” Create the matrix with “r” rows and “c” columns and assign the elements with the third argument "v[]", which is a double 2D array. You need to do some checking to make sure the input 2D array should have the rows and columns with the same values as or greater values than the first two input arguments. It is fine if the input 2D array contains more numbers than the specified “r” rows and “c” columns needed. You can simply ignore those extra numbers. (Hint: to check the size of the array, use the "length" data member of an array object)
The code I have so far is as follows:
Matrix(int r, int c, double v[][]) {
//Implementation here...
rows = r;
cols = c;
}
I'm already thinking that I should add values=v;
, then using .length to check the array somehow. This is one part I'm stuck on, as I'm not sure how to check both of the 2D array's dimensions separately. When I get this part, I'm planning on simply writing an if statement that first checks if r is less than or equal to the first length value of the array, then checking if c is less than or equal to the second length of the array. Any help filling in the blanks or checking what I have would be much appreciated.
Upvotes: 0
Views: 1983
Reputation: 695
The solution to the problem is already given, This is how it works behind the scene.
A 2D array is really an array of pointers, where each pointer can refer to a one-dimensional array. Those one-dimensional arrays are the rows of the 2D array
eg: int A[][] = new int[3][4]
So when you write A.length
it gives you the length of the rows. and when you specifically write A[0].length
it says give me the length of the array on A[0]
position.
which is the column of the array.
Upvotes: 1
Reputation: 529
Assuming all columns are of same length, You can use:
int rows = v.length;
int cols = v[0].length;
And then you can check if r
& c
are equal to or greater than rows
& cols
respectively.
Upvotes: 1