Created
October 16, 2019 16:32
-
-
Save parzibyte/60961038f336367cf0cf1f8c91c1777b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
/* | |
* Buscar elemento en arreglo de C | |
* | |
* https://parzibyte.me/blog | |
* | |
* */ | |
int buscarEnArreglo(const int arreglo[], int busqueda, int longitud); | |
int main(void) { | |
// El arreglo en donde buscamos | |
int edades[] = {23, 25, 30, 15, 2}; | |
// El valor que buscamos | |
int busqueda = 25; | |
// La longitud; puedes indicarla manualmente o calcularla con | |
// sizeof como se ve en https://parzibyte.me/blog/2018/09/21/longitud-de-un-arreglo-en-c/ | |
int longitud = sizeof edades / sizeof edades[0]; | |
int existe = buscarEnArreglo(edades, busqueda, longitud); | |
printf("Posicion de %d en arreglo: %d", busqueda, existe); | |
return 0; | |
} | |
/* | |
Esta función regresa el índice del elemento buscado | |
dentro del arreglo; si no lo encuentra regresa -1 | |
Recibe el arreglo, la búsqueda y la longitud del arreglo, | |
recuerda que la longitud se debe pasar porque al pasar por | |
referencia no se puede obtener la longitud | |
*/ | |
int buscarEnArreglo(const int arreglo[], int busqueda, int longitud) { | |
for (int x = 0; x < longitud; x++) { | |
if (arreglo[x] == busqueda) return x; | |
} | |
return -1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment