Problem with linear search

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.


#include<iostream>
using namespace std ;

const int SIZE = 9 ;

int GetNum() ;
bool LSearch(int [], int) ;
void ShowResult(bool) ;

int Data[SIZE] = {5658845, 8080152, 1005231,
4520125, 4562555, 6545231,
7895122, 5552012, 3852085} ;

int main()
{
int number ;
number = GetNum() ;

bool Search ;
Search = LSearch(Data, number) ;
ShowResult(Search) ;

cin.get() ;
cin.get() ;
return 0 ;
}

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" ;
}



This line:
while ( found == false || i < SIZE)

Should be:
while ( found == false && i < SIZE)

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])
{
return true ;
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;

This line:
if (search == true)

Can be simplified to:
if (search)
Thank you Pulse. You helped me a lot. I will take your advice.
Have a good day, Pulse. :)
Topic archived. No new replies allowed.