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, inmain()
or in the function. - You pass the arguments into the function in the wrong order. You are:
- passing
n
(frommain()
) into the unusedz
value - searching for the uninitialised
z
(frommain()
) - 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
)
- passing
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