Search code examples
arrayscincrement

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?


Solution

  • 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.