OneBite.Dev - Coding blog in a bite size

Count The Number Of Occurrences Of A Specific Element In An Array In C++

Code snippet for how to Count The Number Of Occurrences Of A Specific Element In An Array In C++ with sample and detail explanation

In programming, we often deal with large data sets where finding specific details can be like searching for a needle in a haystack. One such detail could be to identify the number of occurrences of a specific element in an array. In this article, we will explore how to perform this task in C++.

Code snippet for Counting Occurrences in an Array

Here is a simple and effective piece of code that does exactly that:

#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    int myArray[10] = {1, 2, 3, 4, 5, 4, 4, 6, 4, 8};
    int n = sizeof(myArray) / sizeof(myArray[0]);
    int x = 4;

    int count = count(myArray, myArray + n, x);
    cout << "4 appears " << count << " times in myArray.";
    
    return 0;
}

Code Explanation for Counting Occurrences in an Array

In the code snippet above, the aim is to find out how many times the number ‘4’ appears in the array named “myArray”. Here is a step by step explanation:

  1. We begin by including the necessary header files. ’’ for input/output capabilities, and ’’ since we are using the ‘count’ function which is defined inside this library.

  2. We define the main function which is the starting point of the program.

  3. Inside the main function, we declare an array ‘myArray’ with 10 elements.

  4. The variable ‘n’ here gets the size of the entire array divided by the size of a single element from the array. This calculation gives us the total number of elements within the array.

  5. We assign the number ‘4’ to the variable ‘x’, that is the number whose occurrences we want to find in the array.

  6. The function ‘count’ is called with three parameters: start of the array, end of the array, and the element to search. This function traverses the range [first, last) and returns the number of occurrences of ‘x’.

  7. Using ‘cout’, the program outputs the count of the number ‘4’ in the array.

  8. Finally, the program exits by returning 0, which signifies successful execution in C++.

Remember to replace ‘4’ and ‘myArray’ with your desired number and array. This versatile code can help you quickly find the number of occurrences of any specific element within an array in C++.

c-plus-plus