Reputation: 75
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.
#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();
}
Upvotes: 0
Views: 127
Reputation: 3024
lets suppose, 4 exists two times in array. in your while loop, when 4 is found once, found variable is set to true. which is the breaking condition of loop. as you have written:
while(loc < length && !found)
This is why, it only finds the digit 4 one time, where it exists twice. try to fix this. (hint: you may use for loop, for ease, or set found=false at the end of each iteration)
And if element is not within the array, it doesn't display it's index. try it carefully again.
Edit: here's the way you do it, as you asked for. replace your while with for and simply you get this working:
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;
for(loc = 0;loc < 5; loc++)
{
if(list[loc]==searchItem)
{
cout << "\n\t\t " << searchItem << " is found at index"<<loc<<endl;
}
else
cout << "\n\n\tThe " << searchItem << " is not in the array"<<endl;
}
Upvotes: 4