Hello everyone, I am a beginner in C++. I am trying to practice my understanding about the linear search algorithm for array. I encounter two problems in this assignment. Firstly, it is always print that the number is valid even though I try to enter an invalid number. Secondly, the program always stop responding whenever I try to enter a number which is more than 3 digits. This is my code, hopefully, you guys can help me find the errors with your experiences. Thank you in advance.
int GetNum()
{
int number ;
do
{
cout << "Please enter your charge account number: " ;
cin >> number ;
if(0 > number)
cout << "The number MUST BE GREATER THAN ZERO AND "
<< "have at least 7 digits." << endl ;
} while (0 > number) ;
return number ;
}
bool LSearch(int array[], int number)
{
int i = 0 ;
bool found = false ;
while ( found == false || i < SIZE)
{
if (number == array[i])
{
return true ;
found = true ;
}
i++ ;
}
if (found == false)
return false ;
}
void ShowResult(bool search)
{
if (search == true)
cout << "Your charge account number IS valid. Congratulation!\n" ;
else
cout << "Your charge account number is NOT valid."
<< " Please re-enter it!\n" ;
}
The reason being is that you want to make sure you haven't found the number yet and that there are still numbers left. If i == size, there are no numbers left to find and if found is true, it will still keep going
It can also be simplified to: while (!found && i < SIZE)
You might also want to consider a for loop if you know how to use them.
These lines:
1 2 3 4 5
if (number == array[i])
{
returntrue ;
found = true ;
}
Once you return from a function, the rest of the code in that function is completely ignored. You don't need found = true;