0

Java Array

A two-dimensional array of ints with 4 rows, has been created and assigned to a2d. Write an expression whose value is the total number of ints that could be stored in the entire array.

22nd Nov 2021, 4:29 AM
Abhishek Kutwal
Abhishek Kutwal - avatar
6 Answers
+ 1
Supposing that the 2d array is CxR sized with C = columns and R = Rows : Total elements would be exactly CxR In your question you don't specify th columns but just the rows, it happens a lot in programming, the thing you could use is the Length property of arrays, use it to know how many columns for each row int totalArrayCells = 0; for(int r = 0; r < array.length; r++) { totalArrayCells = totalArrayCells + array[r].length; } This works without knowing either rows and columns
22nd Nov 2021, 9:01 AM
[Dev] DJREMiX6
[Dev] DJREMiX6 - avatar
+ 1
Coding Cat It will only if all the rows have the same number of columns, let's suppose you have a 2d array with 3 rows Row 0 with 3 columns, Row 1 with 6 columns, Row 2 with 1 column If you do array.length * array[0].length it will return 9 but you actually have 10 columns so this works only if each row have the same number of columns, but my solution where you iterate through alle the rows and for each row you iterate through all the columns, you just don't care abou how many there are because it is calculated at runtime
22nd Nov 2021, 10:48 AM
[Dev] DJREMiX6
[Dev] DJREMiX6 - avatar
+ 1
[Dev] DJREMiX6 yes, you are right. That's a good point. My solution is only good for the special case where all rows have a identical length. Your one is generally working. (btw I hate 2d arrays with differend row lengths 😉)
22nd Nov 2021, 11:23 AM
Coding Cat
Coding Cat - avatar
+ 1
Coding Cat Yeah everyone does but we all have to work with them LOL
22nd Nov 2021, 11:24 AM
[Dev] DJREMiX6
[Dev] DJREMiX6 - avatar
0
How can you calculate that when no info available about number of columns per row?
22nd Nov 2021, 6:19 AM
Ipang
0
Yes [Dev] DJREMiX6 , looking at your solution, I think array.length * array[0].length could also give the total numbers of cells. Or I'm wrong?
22nd Nov 2021, 10:25 AM
Coding Cat
Coding Cat - avatar