array counting

i have difficulty understanding the logic especially in this part
for(int i=0;i<size;++i)
distrib[numbers[i]] +=1;
can someone please give a clear understaning of this ,i been thinking about it for some time now and still i can't understand
thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
  void buildArray(int arr[],int size ) {
        srand(time(NULL));
        for(int i=0;i<size;++i)
            arr[i]=rand() % 100 +0;
}

void initArray(int arr[],int size) {
        for(int i=0;i<size;++i)
            arr[i]=0;
}

void displayArray(int arr[],int size) {
        for(int i=0;i<size;++i)
            cout << i << ": " <<arr[i]<<endl;
}

int main()
{
    const int size =101;
    int numbers[size];
    buildArray(numbers,size);
    cout <<endl;
    displayArray(numbers,size);
    cout << endl;
    int distrib[size];
    initArray(distrib,size);

        for(int i=0;i<size;++i)
          distrib[numbers[i]] +=1;
    displayArray(distrib,size);
        cout << endl;
Some of the elements of the distrib will be increased so many times as they are contained in numbers array.
why distrib[numbers[i]] +=1;
i don't get it ??
Well, numbers is an array of random numbers.
numbers[i] is element number i in the list (a random number). Using i means that every number in numbers is used once.
distrib[numbers[i]] means the numbers[i]th element in distrib.
+= 1 means increase by one.
distrib[0] is how many times 0 appears in numbers
distrib[1] is how many times 1 appears in numbers
distrib[x] is how many times x appears in numbers

So, the loop iterates through numbers (by using i) and increases the tally of how many times each number has appeared with +=1
TL;DR: The code is counting the frequency of each random number.
Topic archived. No new replies allowed.