Wea 44
Wea 44

Reputation: 15

Increment of array inside array in C

#include <stdio.h>

#define NUMBER 20                                         

#define OPTION 6 

void main ()
{

    int optionList[NUMBER]= 
        {4,4,5,2,1,3,1,0,4,3,3,1,2,5,4,2,3,4,3,1}; 

    int count[OPTION] = { 0 } ;

    for (int i = 0; i <= NUMBER-1; i++) 
        ++count[optionList[i]]; 
} 

I don't understand ++count[optionList[i]]. Is it a loop increment for both array 'count 'and 'optionList'? How does it work?

Upvotes: 0

Views: 214

Answers (2)

Natrix
Natrix

Reputation: 113

optionList - is an array of 20 elements
count - is an array of 6 elements

the for loop iterates over i = 0 to inclusively i = 20 - 1 = 19.
In each iteration step it executes ++count[optionList[i]];

Let's calculate ++count[optionList[i]]; for i=3 step by step: First we look at optionList[i], so we take the i-th element from optionList. The 3rd element from optionList (beginning to count from 0) is 2. So ++count[optionList[i]] evaluates to ++count[2]. ++value means incrementing the value behind value by one. ++count[2] means that the 2nd element from count is increased by one. So after executing ++count[optionList[i]]; the array count now looks like this: {0, 0, 1, 0, 0, 0} (if it looked like this {0, 0, 0, 0, 0, 0} before)

Conclusion

Look at optionList as an array of indices. The loop increments count at every index from optionList.

Upvotes: 2

user14880435
user14880435

Reputation: 21

It you think about this from the "inside out" way, the optionList[i] gets evaluated first. This returns the value at optionList[i]

ex) If i = 0, optionList[i] = 4

Then the count[{value}] gets evaluated.

ex) If i = 0, optionList[i] = 4. count[optionList[i]] is the same as count[4] in this case.

So the fourth spot in the count array then gets incremented by the prefix ++. The loop essentially goes through and increments the value of the count array at each location specified by optionList[i].

Upvotes: 1

Related Questions