Hi
i was following a tutorial but i stuck at something i don't understand it
This is to find out how many times a number appeered inside an array

sorry for my English

#include <iostream>
#include <conio.h>

using namespace std;

int main()
{
    const int size = 5;
    int arr[size] = { 0, 0, 0, 0, 0 };
    int num[size] = { 1, 4, 5, 1, 4 };
    for (int i = 0; i < size; ++i)
    {
        arr[num[i]] += 1; //I don't understand this part, doesn't this suppossed to to increase each value in arr[5] by 1?
    }
    for (int i = 0; i < size; ++i)
    {
        cout << i << ": " << arr[i] << endl;
    }
    _getch();
    return 0;
}

When i is 0, we get arr[num[0]] += 1. num[0] is 1, so we get arr[1] += 1. By the same logic we get arr[4] += 1 when i is 1 and so on.

So no, it doesn't increase each element of arr by 1. Rather it increases each element in arr once for each time its index appears in num. So for example arr[1] is incremented twice because 1 appears twice in num and arr[0] is never increment because there is 0 in num.

Also, 5 is never counted because arr[5] is out of bounds.

Edited 2 Years Ago by nullptr

Comments
Seems like I missed the point of the question.
This question has already been answered. Start a new discussion instead.