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
Show 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.