Grupo
Algoritmos de Búsqueda y Ordenación en C++
Ojetivo
Escriba una función en C++ que acepte un array y un número objetivo como entrada, y que devuelva el número de veces que dicho número aparece en el array. Debe iterar sobre el array, comparar cada elemento con el objetivo y mantener un contador que se incremente cada vez que se encuentra el objetivo.
Desarrolle una función que cuente cuántas veces aparece un número en un array.
Ejemplo de Código C++
Mostrar Código C++
#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;
}
Salida
The number 2 appears 4 times in the array.
Comparte este ejercicio C++