0

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;
}
3
Contributors
3
Replies
25
Views
3 Years
Discussion Span
Last Post by Sarkurd
1

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.

1

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

Edited by nullptr

Votes + Comments
Seems like I missed the point of the question.
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.