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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include<iostream>
#include<conio.h>

using namespace std;

int main()
{
    int list[5], a, loc = 0, searchItem, listLength;
    bool found = false;

    cout<<"Enter 5 numbers: "<<endl;
    for(a = 0; a < 5; a++)
               cin >> 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:

1
2
3
4
5
6
7
for(counter = 0; counter < listLength; ++counter)
{
   if(element found)
{
  print the position
}
}
Last edited on
I revised the code and came up with this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include<iostream>
#include<conio.h>

using namespace std;

int main()
{

int list[5], a, loc = 0, searchItem, listLength;
bool found = false;

cout<<"Enter 5 numbers: "<<endl;
for(a = 0; a < 5; a++)
           cin >> 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.