Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How nested array in a loop will work

Tags:

java

arrays

loops

I am trying to understanding the working of this array in a loop

for (int answer=0; answer<responses.length; answer++)
{
++frequency[responses[answer]]
}

Frequency is an array initialized in start as

int [] frequency = new int [6];

We also have responses as an array having values int[] responses= {1,2,3,4,4,4,4,4}

I am not understanding how this ++frequency[responses[answer]] works, it look to me nested array but how it will work ?

like image 922
AHF Avatar asked Apr 26 '26 22:04

AHF


1 Answers

There is no nested arrays. You are just nesting two array access syntaxes.

To explain this code, we first need to know how will the answer variable change. From the for loop header, we can see that it starts from 0, and goes all the way up to responses.length - 1, which is 8. Now we can evaluate the expression frequency[responses[answer]]:

// in each iteration of the loop
frequency[responses[0]]
frequency[responses[1]]
frequency[responses[2]]
frequency[responses[3]]
frequency[responses[4]]
frequency[responses[5]]
frequency[responses[6]]
frequency[responses[7]]

Now we can evaluate the responses[x] part. We just need to find the corresponding response in the responses array. responses[0] is the first item, which is 1.

frequency[1]
frequency[2]
frequency[3]
frequency[4]
frequency[4]
frequency[4]
frequency[4]
frequency[4]

The statement also includes the ++ operator, which increments that particular index of frequency by 1. So all of the above indices will be incremented by 1 one after another, making the frequency array look like this:

[0, 1, 1, 1, 5, 0]

On a higher level of abstraction, this code is counting how many times a particular response appears in the responses array. For example, 4 appeared 5 times.

like image 95
Sweeper Avatar answered Apr 28 '26 10:04

Sweeper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!