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
Try this:
int passwdSearch(Eidos pinPro[], int pass)
{
for(int i=0; i<N; i++)
{
if(pinPro[i].getPasswd()==pass)
return i;
}
return -1;
}
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;
}
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.