Shateel - 2 months ago 6

C Question

I need help to understand this code clearly, please help. I can't figure out how this program keep track of how many number has given in responses array.

I don't understand what's going on the for loop and specially this line ++frequency[responses[answer]];

`#include<stdio.h>`

#define RESPONSE_SIZE 40

#define FREQUENCY_SIZE 11

int main(void)

{

int answer; /* counter to loop through 40 responses */

int rating; /* counter to loop through frequencies 1-10 */

/* initialize frequency counters to 0 */

int frequency[FREQUENCY_SIZE] = {0};

/* place the survey responses in the responses array */

int responses[RESPONSE_SIZE] = {1,2,6,4,8,5,9,7,8,10,1,6,3,8,6,10,3,8,2,7,6,5,7,6,8,6,7,5,6,6,5,6,7,5,6,4,8,6,8,10};

/* for each answer, select value of an element of array responses

and use that value as subscript in array frequency to determine element to increment */

for(answer = 0 ; answer < RESPONSE_SIZE; answer++){

++frequency[responses[answer]];

}

printf("%s%17s\n", "Rating", "Frequency");

/* output the frequencies in a tabular format */

for(rating = 1; rating < FREQUENCY_SIZE; rating++){

printf("%6d%17d\n", rating, frequency[rating]);

}

return 0;

}

Answer

`++frequency[responses[answer]]`

is a dense way of writing

```
int r = response[answer];
frequency[r] = frequency[r] + 1;
```

with the caveat that `frequency[r]`

is only evaluated once.

So, if `answer`

equals `0`

, then `responses[answer]`

equals `1`

, so we add `1`

to `frequency[1]`

.

**Edit**

The following table shows what happens to `frequency`

through the loop (old value => new value):

```
answer response[answer] frequency[response[answer]]
------ ---------------- ---------------------------
0 1 frequency[1]: 0 => 1
1 2 frequency[2]: 0 => 1
2 6 frequency[6]: 0 => 1
3 4 frequency[4]: 0 => 1
... ... ...
10 1 frequency[1]: 1 => 2
```

etc.

Source (Stackoverflow)

Comments