• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Arrays...

 
sonir shah
Ranch Hand
Posts: 435
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If size = 4, triArray looks like:

a)
1 2 3 4
5 6 7
8 9
10
b)
1 4 9 16
c)
1 2 3 4
d)
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
e)
1
2 3
4 5 6
7 8 9 10

I cannot understand what the question is trying to say?
Can any one will help me out here?..
 
Junilu Lacar
Bartender
Pie
Posts: 7300
44
Android Eclipse IDE IntelliJ IDE Java Linux Mac Scala Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sonir,
I hope you got enough rest for your exam today.
The answer is (e).
The makeArray method creates the following array:
{
{1},
{2, 3},
{4, 5, 6},
{7, 8, 9, 10}
}
Notice the outer array has 4 elements. This results from the statement
int[][] triArray = new int[size][];
Which, when size=4, translates to "create an array that can hold 4 arrays of int".
The for (int i ... ) loop just iterates through these four elements. During each iteration, the following happens:
A new array of int is created and assigned to the
ith element of the outer array in the statement
triArray[i] = new int[i+1]
E.g., when i = 0, the above would evaluate to
triArray[0] = new int[1]; // nested array holds 1 int
and when i = 3, it would evaluate to'
triArray[3] = new int[4]; // nested array holds 4 ints
The for (int j ... ) loop simply assigns values (using and incrementing val) to the elements of the new nested array.
HTH
 
Younes Essouabni
Ranch Hand
Posts: 479
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I do totally agree with Junilu.
int[][] triArray = new int[size] [];//At this point you create an array of 2 dimension
for( int i = 0; i < triArray.length; i++ )//In an array of 2 dimension, Array.length will always refer to the first [] of the array, hence size.
triArray[i] = new int[i+1];// Not much to explain
for( int j=0; j < triArray[i].length; j++ )// An array of 2 dimension is in fact an array inside an array, so triArray[i].length refer to the second dimension of the array. The first time the value of triArray[i].length will be 1, second time 2,... Because each time you create an array of that dimension inside the outer array. You do it at this line: triArray[i][j] = val++;
If you want to see the execution of the code you can use the code provided here:

I hope it helped you!!!
See you soon
Younes
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic