What is the output from this program?
double[] w = new double[ 4 ];
w[ 0 ] = 5.0;
w[ 1 ] = (2 * w[ 0 ]);
w[ 2 ] = (2 * w[ 1 ]);
w[ 3 ] = (2 * w[ 2 ]);
System.out.println( w[ 2 ] + w[ 3 ] );
w[ 0 ] = 5.0;
w[ 1 ] = (2 * w[ 0 ]);
w[ 2 ] = (2 * w[ 1 ]);
w[ 3 ] = (2 * w[ 2 ]);
System.out.println( w[ 2 ] + w[ 3 ] );
I got 5 wrong because of an off by one error. I answered 30 because I thought the array position system was 1,2,3,4 instead of 0,1,2,3. if I had done the problem correctly I would have gotten 60 instead.
9)
After the following code executes, what is the value of a[ 3 ][ 2 ]?
int[][] a =
{
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 }
};
{
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 }
};
In this one I mixed up the coordinate system and thought of it mathematically thinking 3 was the column number and that 2 was the row number. in actuality 3 is the row number and 2 is the column number therefore the answer should have been 10.
I'm a big fan of an old joke that runs like this:
ReplyDeleteA pedestrian walking along Fifty-seventh Street in Manhattan stops Arthur Rubinstein and asks, "Could you tell me how to get to Carnegie Hall?" "Yes," says the maestro. "Practice, practice, practice!"
I'm a bit surprised that you slipped up on the indexing counting from 0, since I know you've seen that before in Java, but you need to make these kinds of mistakes enough times, and then catch your error, so that you stop making them. There are actually other languages that index from 1 (Fortran and Pascal both do), but Java is not one of them.
For your second example, let me suggest a different approach. The indexing operation on variable a proceeds from left to right, so a[3] accesses an element of a (the 4th element, since we count from 0 in Java ;-). Write that down. It is {13, 14, 15, 16} in this case. a[3][2] is only legal because a[3] is indexable. You don't need to think in terms of rows and columns here. That is an abstraction that doesn't really help in this case.