3

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 ?

2 Answers 2

1

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.

0

The expession

++frequency[responses[answer]]

is exactly the same as if it had been written

int fi = responses[answer];
++frequency[fi];

frequency has six elements, and all the entries in responses are valid indices for a six-element array. answers has eight elements, so as long as answer is between 0 and 7, the whole thing will work.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.