Searching
Aug 12, 2014 at 2:59am UTC
User input: 1, 2, 3, 4, 5
How do I display "Target Found" when user entered 3? I get the output like this when user searched 3. I know it is because of for loop but I didn't get the correct output when I delete for loop.
Output:
Target not found
Target not found
Target found
Target not found
Target not found
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 33 34 35 36 37 38 39
#include <iostream>
using namespace std;
class student
{
public :
int id[5], marks[5], target;
};
int main()
{
student a;
int i;
cout<<"Please enter students' id and marks : " <<endl;
cout<<endl;
for (i=0; i<5; i++)
{
cout<<"Student " << i+1 << " ID: " ;
cin>>a.id[i];
cout<<"Student " << i+1 << " mark: " ;
cin>>a.marks[i];
}
cout<<endl;
cout<<"Enter the student's ID that you want to search: " ;
cin>>a.target;
for (i=0; i<5; i++) //the loop is wrong
{
if (a.id[i] == a.target)
cout<<"Target found" <<endl;
else
cout<<"Target not found" <<endl;
}
}
Last edited on Aug 12, 2014 at 3:00am UTC
Aug 12, 2014 at 5:37am UTC
31 32 33 34 35 36 37 38 39 40 41
bool found = false ;
for (i=0; i<5; i++) //the loop is wrong
{
if (a.id[i] == a.target) {
cout<<"Target found" <<endl;
found = true ;
}
}
if (!found)
cout<<"Target not found" <<endl;
Topic archived. No new replies allowed.