### Sequential search problem

Hello guys I'm here to seek for help to finish my program. Well the code below runs but it doesn't perform all of the tasks it should do. The program should ask the user to input 5 numbers to be stored in an array. Second, it should ask the user what number inside the array he wants to find. After that, if the number is found in the array, it should display its location (index/indexes) and if not, it should display that the number is not within the array.

My problem is that even though the number to be searched is not within the array, it still displays an index. And another problem is that when I input common numbers in an array for example I want to search for 3: {3,3,54,0,8} it just displays the index of the "first" number three and doesn't display the index of the "second" number three. Please help me thanks.

 ``123456789101112131415161718192021222324252627282930`` ``````#include #include using namespace std; int main() { int list[5], a, loc = 0, searchItem, listLength; bool found = false; cout<<"Enter 5 numbers: "<> list[a]; cout<<"\n\tEnter the number you want to find :"; cin>>searchItem; while(loc < listLength && !found) if(list[loc] == searchItem) found = true; else loc++; if(found) cout << "\n\t\t " << searchItem << " is found at index " << loc << endl; else cout << "\n\n\tThe " << searchItem << " is not in the array" << endl; getch(); }``````
You have not initialized listLength;

EDIT:

 ``1234567`` ``````for(counter = 0; counter < listLength; ++counter) { if(element found) { print the position } }``````
Last edited on
I revised the code and came up with this:

 ``1234567891011121314151617181920212223242526272829303132`` ``````#include #include using namespace std; int main() { int list[5], a, loc = 0, searchItem, listLength; bool found = false; cout<<"Enter 5 numbers: "<> list[a]; cout<<"\n\tEnter the number you want to find : "; cin>>searchItem; while(loc < 5 && !found){ if(list[loc] == searchItem) { cout << "\n\t\t " << searchItem << " is found at index " << loc << endl; found = true; } else loc++; cout << "\n\n\tThe " << searchItem << " is not in the array" << endl; } getch(); }``````

The problem is that when I input common numbers in the array, it still reads the first index and ignores the second one
irrespective of whether you find the number or not you have to increment loc.. thats why i suggested yo to use for loop..

GN..
Topic archived. No new replies allowed.