How to Count the Number of Occurrences of a Value in an Array in C++? (original) (raw)

Last Updated : 18 Mar, 2024

In C++, an array is a data structure that stores the collection of the same type of data in a contiguous memory location. In this article, we will learn how to count the number of occurrences of a value in an array in C++.

**Example:

**Input:
arr= {2, 4, 5 ,2 ,4 , 5, 2 , 3 ,8}
Target = 2

**Output:
Number of occurences of 2 are : 3

Count the Number of Occurrences in an Array in C++

To count the number of occurrences of a specific value in an array, we can use a simple for loop while looking for our target value. If the target value is found, we increment the counter variable. We do this till the whole array is scanned.

**Approach

**C++ Program to Count the Number of Occurrences of a Value in an Array

The below example demonstrates how we can count the total number of occurrences of a value in an array.

C++ `

// C++ Program to illustrate how to count the number of // occurrences of a value in an array #include using namespace std;

int main() {

// initializating an Array
int arr[] = { 2, 4, 5, 2, 4, 5, 2, 3, 8 };

// Calculating the size of the array
int n = sizeof(arr) / sizeof(arr[0]);

// Defining the target number to search for
int target = 2;
// Initialize a counter
int counter = 0;

// Loop through the array elements
for (int i = 0; i < n; i++) {
    // Check if the current element equals the target
    // number
    if (arr[i] == target) {
        counter++;
    }
}

// Output the result
cout << "Number " << target << " occurs " << counter
     << " times in the array.";

return 0;

}

`

Output

Number 2 occurs 3 times in the array.

**Time Complexity: O(n), here n is the number of elements in the array.
**Auxilliary Space: O(1)

Similar Reads