0

I'm trying to determine the number of times an integer occurs in an array, but I'm getting some unexpected results.

For example:

int arr1[10] = {1, 2, 2, 4, 4, 2, 5, 10, 2, 6};
std::cout << getOccurrences(arr1, 2) << std::endl; //should be 4

Here is the full code:

#include "stdafx.h"
#include <iostream>
#include <array>

int getOccurrences(int arr[], int ch) {
    int count = 0;
    for (int i = 0; i < sizeof(arr); i++) {
        if (arr[i] == ch) {
            count++;
        }
    }

    return count;
}


int main() {
    int arr1[10] = {1, 2, 2, 4, 4, 2, 5, 10, 2, 6};
    int arr2[10] = { 10, 21, 24, 44, 43, 24, 50, 10, 2, 6 };
    int arr3[10] = { 11, 22, 22, 43, 44, 22, 51, 11, 2, 6 };
    int arr4[10] = { 12, 12, 12, 4, 4, 12, 5, 10, 12, 6 };
    int arr5[10] = { 21, 21, 21, 4, 4, 21, 5, 10, 21, 6 };
    std::cout << getOccurrences(arr1, 2) << std::endl; //should be 4
    std::cout << getOccurrences(arr2, 10) << std::endl; //should be 2
    std::cout << getOccurrences(arr3, 22) << std::endl; //should be 3
    std::cout << getOccurrences(arr4, 12) << std::endl; //should be 4
    std::cout << getOccurrences(arr5, 21) << std::endl; //should be 5

    return 0;
}

However, after running this I get:
2
1
2
3
3

Can someone explain to me why this is happening? Thanks.

0 Answers0