[Solved] C++ code malfunctioning


This is your search function correctly formatted:

int linearsearch (int A[] , int z, int n, int srchElement) 
{
    for (int z = 0; z < n; z++)
    {
        if(A[z] == srchElement)
            {return z;}
    } 
    return -1;
}

and here is how you call it:

index=linearsearch(A, n, srchElement, z);
  • You pass a value z in with the call. It is unitialised and does nothing, in main() or in the function.
  • You pass the arguments into the function in the wrong order. You are:
    • passing n (from main()) into the unused z value
    • searching for the uninitialised z (from main())
    • passing in the element you are looking for as n (array size). (This will quite likely result in out of bounds error, e.g. if searching for -1)

Try this:

int linearsearch (int A[], int n, int srchElement) 
{
    for (int z = 0; z < n; z++)
    {
        if(A[z] == srchElement)
            {return z;}
    } 
    return -1;
}

and here is how you call it:

index=linearsearch(A, n, srchElement);

solved C++ code malfunctioning