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

In this exercise, you will develop a C++ function that counts how many times a specific number appears in an array. This task involves iterating through the array, comparing each element with the target number, and incrementing a counter each time a match is found. This is a common task in many algorithms and can be used to analyze data, check for duplicates, or track the frequency of certain elements in a dataset. By implementing this function, you will practice basic array manipulation and control structures like loops and conditionals in C++.

Group

Search and Sort Algorithms in C++

Objective

Write a C++ function that accepts an array and a target number as input and returns the number of times the target number appears in the array. You need to iterate over the array, compare each element with the target, and maintain a counter that is incremented each time the target is found.

Develop a function that counts how many times a number appears in an array.

Example C++ Exercise

 Copy C++ Code
#include <iostream>  // Include the input-output stream library
#include <vector>     // Include the vector library to use dynamic arrays
using namespace std;

// Function to count the occurrences of a specific number in an array
int countOccurrences(const vector<int> &arr, int target) {
    int count = 0;  // Initialize the counter to 0

    // Loop through the array to check each element
    for (int i = 0; i < arr.size(); i++) {
        // If the current element matches the target number
        if (arr[i] == target) {
            count++;  // Increment the counter
        }
    }
    
    return count;  // Return the final count of occurrences
}

int main() {
    // Define an array of numbers
    vector<int> arr = {1, 2, 3, 4, 2, 5, 2, 6, 7, 2};

    // Define the target number to search for
    int target = 2;

    // Call the countOccurrences function and store the result
    int result = countOccurrences(arr, target);

    // Output the result
    cout << "The number " << target << " appears " << result << " times in the array." << endl;

    return 0;
}

 Output

The number 2 appears 4 times in the array.

Share this C++ Exercise


More C++ Programming Exercises of Search and Sort Algorithms in C++

Explore our set of C++ Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C++. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C++.