Page 1 of 1

Question about Nested Loops

Posted: Fri Dec 29, 2023 1:32 pm
by aks0961
Hi, I am currently looking through nested loops and I am running into a question that I was hoping to get rectified.

On page 166 of the book you are going through 14 steps outlining how to tackle the nested loop example on the previous page. In these steps, in order to find the value of the sum variable, for example, you say " sum is assigned 5 + values[3][0]" and you then mention this evaluates to 5+4.

The doubt that I am running into is that I don't really understand how you are evaluating the "values[3][0]" part to 4. Can you please help me with this, and just help me understand how this works? Thanks

Re: Question about Nested Loops

Posted: Fri Dec 29, 2023 10:57 pm
by admin
values is an array of arrays (could be called a two dimensional array for simplicity) and it is initialized as:

Code: Select all

int[][] values = { {1, 2, 3} , { 2, 3}, {2 }, { 4, 5, 6, 7 } };
So, values[0] points to an array containing {1, 2, 3}, values[1] points to an array containing {2, 3}, values[2] points to an array containing {2}, and values[3] points to an array containing {4, 5, 6, 7 }.

Now, values[3][0] is the first element of the array pointed to by values[3]. Thus, values[3][0] is 4.

Accessing arrays is explained in the arrays chapter. You might want to go through that chapter and then come back to this you have any confusion.