Grupo
Arrays y Vectores en C++
Ojetivo
1. Define un array con varios valores enteros.
2. Crea una función que tome el array y el número objetivo como entrada.
3. Recorre el array y compara cada elemento con el número objetivo.
4. Si se encuentra el número objetivo, imprime su índice.
5. Si no se encuentra el número objetivo, imprime un mensaje indicando que no está en el array.
6. Prueba el programa con diferentes arrays y números objetivo.
Implementa un programa que busque un número en un array.
Ejemplo de Código C++
Mostrar Código C++
#include <iostream> // Include iostream for input and output
using namespace std; // Use the standard namespace
// Function to search for a number in an array
int searchNumber(int arr[], int size, int target) {
// Loop through the array to find the target number
for (int i = 0; i < size; i++) {
if (arr[i] == target) { // If the number is found
return i; // Return the index of the found number
}
}
return -1; // Return -1 if the number is not found
}
int main() {
// Define an array of numbers
int numbers[] = {1, 3, 5, 7, 9, 11};
int size = sizeof(numbers) / sizeof(numbers[0]); // Calculate the size of the array
int target = 7; // Set the number to search for
// Call the function to search for the target number
int index = searchNumber(numbers, size, target);
// Check if the number was found and print the result
if (index != -1) {
cout << "Number " << target << " found at index " << index << endl;
} else {
cout << "Number " << target << " not found in the array." << endl;
}
return 0; // End of program
}
Salida
Number 7 found at index 3
Comparte este ejercicio C++