Problem with functions - Find item in a fix

0

How about, very good day, I've been starting to program, and I've had a problem with a program regarding functions.

It turns out that they ask me to make a program that stores elements in an array, and then asks the user to enter a number to look for it in the array. If the number entered is in the array, show it, and also show the location of that number.

The program works well for 4 elements in the array, but when you enter 5 elements, there is a problem, because by showing the location of the number entered for your search in the array, it always shows me that it is in position 4.

I hope you can help me, thank you very much.

I append the code below.

#include <stdio.h>
#include <iostream>
void buscarElemento(int a[], int size, int element_Busqueda);

int main()
{
    int n; // Variable que determinará el número de elementos del arreglo.
    int i; // Variable para recorrer el arreglo.
    int elemento;

    int array[n]; // Creamos un arreglo de enteros, el número de elementos del arreglo
              // será el número asignado a la variable 'n'.

    printf("Ingresa el numero de elementos del arreglo: ");
    scanf("%d",&n);

    for(i=0; i<n; i++)
    {
        printf("Ingresa el elemento numero %d del arreglo: ", (i+1) );
        scanf("%d",&array[i]);
    }

    printf("\n\n");

    printf("Ingresa el elemento a buscar en el arreglo: ");
    scanf("%d",&elemento);

    buscarElemento(array, n, elemento);

    system("pause");
    return 0;
}

void buscarElemento(int a[], int size, int element_Busqueda)
{
    int j;
    int b = 0;
    int hold1,hold2;

    while(b == 0)
    {
        for(j=0; j<size; j++)
        {
            if(element_Busqueda == a[j])
            {
                hold1 = a[j];
                hold2 = j;
                b=1;
            }
        }
    }

    if(b==1)
    {
    printf("El elemento encontrado es %d y se encuentra en la posicion %d.",hold1,hold2);
    }
}
    
asked by Jesús Fragoso 13.12.2016 в 23:16
source

2 answers

3

The first thing I mention is that your code is not C simply because you have included the iostream library, which is typical of C ++. You must remove this library so that the code is compilable in C.

int n; // 1

int array[n]; // 2
  • you do not assign a value to n , then it will have a residual value (garbage) that you do not control at all.

  • You create an array with the size given by n (which we remember is not initialized). What would happen if it turns out that n has a negative value? What if n was worth 0?

  • What happens is that the array is created at the same time you declare it, no matter how much you change the value of n , the array is already created and will remain unmovable.

    To solve this problem you can choose:

  • Create the array once you have initialized n (this solution is not compatible with C ++):

    int n; // Variable que determinará el número de elementos del arreglo.
    
    printf("Ingresa el numero de elementos del arreglo: ");
    scanf("%d",&n);
    
    int array[n]; // Creamos un arreglo de enteros, el número de elementos del arreglo
                  // será el número asignado a la variable 'n'.
    
  • Create an array of a size large enough to guarantee that it will not fail (this solution is only applicable if the range of possible values is limited):

    int n; // Variable que determinará el número de elementos del arreglo.
    
    int array[50]; // Creamos un arreglo de 50 enteros.
    
    printf("Ingresa el numero de elementos del arreglo: ");
    scanf("%d",&n);
    
  • You use dynamic memory. The great advantage of using dynamic memory is that you can resize the array at will, the disadvantage is that you have to correctly manage the memory to avoid memory leaks:

    int n; // Variable que determinará el número de elementos del arreglo.
    
    printf("Ingresa el numero de elementos del arreglo: ");
    scanf("%d",&n);
    
    int *array = (int*)malloc(n*sizeof(int)); // Creamos un arreglo de enteros, el número de elementos del arreglo
                  // será el número asignado a la variable 'n'.
    
    // ...
    
    free(array); // Liberamos la memoria reservada con malloc
    
  • More little things:

    while(b == 0)
    {
        for(j=0; j<size; j++)
        {
            if(element_Busqueda == a[j])
            {
                hold1 = a[j];
                hold2 = j;
                b=1;
            }
        }
    }
    

    What happens if you try to find an element that does not exist in the array? That you will enter an endless loop since b always will be worth 0.

    What happens if the item is duplicated? You will return the position corresponding to the last appearance.

    The endless loop problem occurs because you have two nested loops. The solution is to eliminate the loop while and for this you have, basically, two options:

  • Use break to exit the loop (another advantage is that you save the variable b :

    for(j=0; j<size; j++)
    {
        if(element_Busqueda == a[j])
        {
            hold1 = a[j];
            hold2 = j;
            break;
        }
    }
    
    if(j<size)
    {
        printf("El elemento encontrado es %d y se encuentra en la posicion %d.",hold1,hold2);
    }
    
  • Modify the condition of for to be composed:

    for(j=0; j<size && b==0; j++)
    {
        if(element_Busqueda == a[j])
        {
            hold1 = a[j];
            hold2 = j;
            b=1;
        }
    }
    
  • answered by 13.12.2016 в 23:41
    0

    There are some parts that are incorrect in your application:

    • int array[n] : you are declaring the array, but you have not initialized the variable n , so it will have an undetermined value, the correct way is to create the matrix after initializing the value of n

    • The implementation of buscarElemento can be improved, it is not necessary the while nor the variable b that you use as a flag, I understand that the function finds the first element that has a value equal to the one that you pass as a parameter, so you should end when it happens, it is best to return the function at that time ( return ).

    Correcting your program with the previous recommendations I show you the following code.

    #include <stdlib.h>
    #include <stdio.h>
    
    void buscarElemento(int a[], int size, int element_Busqueda);
    
    int main()
    {
        int n; // Variable que determinará el número de elementos del arreglo.
        int i; // Variable para recorrer el arreglo.
        int elemento;
    
    
    
        printf("Ingresa el numero de elementos del arreglo: ");
        scanf("%d",&n);
    
        int array[n]; // Creamos un arreglo de enteros, el número de elementos del arreglo
        // será el número asignado a la variable 'n'.
    
        for(i=0; i<n; i++)
        {
            printf("Ingresa el elemento numero %d del arreglo: ", (i+1) );
            scanf("%d",&array[i]);
        }
    
        printf("\n\n");
    
        printf("Ingresa el elemento a buscar en el arreglo: ");
        scanf("%d",&elemento);
    
        buscarElemento(array, n, elemento);
    
        system("pause");
        return 0;
    }
    
    void buscarElemento(int a[], int size, int element_Busqueda)
    {
        int j;
        int hold1,hold2;
    
    
        for(j=0; j<size; j++)
        {
            if(element_Busqueda == a[j])
            {
                hold1 = a[j];
                hold2 = j;
                printf("El elemento encontrado es %d y se encuentra en la posicion %d.",hold1,hold2);
                return;
            }
        }
    }
    
        
    answered by 13.12.2016 в 23:40