Skip to content

Instantly share code, notes, and snippets.

@parzibyte
Created June 20, 2019 16:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save parzibyte/af936054792f371a8f0b18da3dc2312f to your computer and use it in GitHub Desktop.
Save parzibyte/af936054792f371a8f0b18da3dc2312f to your computer and use it in GitHub Desktop.
#include <iostream>
// Función que busca dentro del arreglo
int buscarElemento(int arreglo[], int longitudDeArreglo, int busqueda) {
for (int i = 0; i < longitudDeArreglo; i++) {
int elementoActual = arreglo[i];
if (elementoActual == busqueda) return i;
}
// Final del ciclo, no encontramos nada así que regresamos
// -1
return -1;
}
int main() {
std::string nombres[] = {
"Luis", "Marijo", "Paco", "Pedro",
};
std::string busqueda = "Luis";
int indice = -1;
for (int i = 0; i < sizeof(nombres) / sizeof(nombres[0]); i++) {
std::string nombreActual = nombres[i];
if (nombreActual == busqueda) {
indice = i;
break;
}
}
if (indice == -1) {
std::cout << "No encontrado\n";
} else {
std::cout << "Encontrado en el indice " << indice << std::endl;
}
// Veamos otro ejemplo con números
// y la función
int numeros[] = {
1, 2, 5, 50, 11, 50, 20,
};
int longitud = sizeof(numeros) / sizeof(numeros[0]), numeroBuscado = 100;
int indiceDeNumeroBuscado = buscarElemento(numeros, longitud, numeroBuscado);
if (indiceDeNumeroBuscado == -1) {
std::cout << "No encontrado\n";
} else {
std::cout << "Encontrado en el indice " << indice << std::endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment