Reputation: 1
i have a problem with a function .. I want the function to have two arguments .. one will be a array of objects and the second one will be the code given by the user and into the function to run a linear search and check if the user's code exists and if the code exists will return his position in the array else returns -1...
this is what i have try already:
int passwdSearch(Eidos pinPro[], int pass)
{
int i=0;
bool found;
found=false;
while(i<N && found==false)
{
if(pinPro[i].getPasswd()==pass)
{
found=true;
return i;
}
else
return -1;
i++;
}
}
i want the function return the position if password exist else return symbolic number -1
The problem is that the code return position only for the first element of array and for the 4 others element function return -1
Upvotes: 0
Views: 360
Reputation: 23
Try this code
int passwdSearch(Eidos pinPro[], int pass)
{
int i=0;
bool found;
found=false;
while(i<N && found==false)
{
if(pinPro[i].getPasswd()==pass)
{
found=true;
return i;
}
else
i++;
}
return -1;
}
Upvotes: 1
Reputation: 2468
Try this:
int passwdSearch(Eidos pinPro[], int pass)
{
for(int i=0; i<N; i++)
{
if(pinPro[i].getPasswd()==pass)
return i;
}
return -1;
}
Upvotes: 3
Reputation: 403
The else will always be activated if the element is not the first one in the array. you should delete it, and return -1 after the while.
int passwdSearch(Eidos pinPro[], int pass)
{
int i=0;
bool found;
found=false;
while(i<N && found==false)
{
if(pinPro[i].getPasswd()==pass)
{
found=true;
return i;
}
}
return -1;
}
This way, if you pass through the whole array and you don't find the required element, then you would return -1.
Edit
And as NathanOliver mentioned, found is useless because you are returning anyways when you find an element. So the code becomes:
int passwdSearch(Eidos pinPro[], int pass)
{
int i=0;
while(i<N)
{
if(pinPro[i].getPasswd()==pass)
return i;
i++;
}
return -1;
}
Upvotes: 0