How can I search for an Item in the array?

If the item is in the array.
Count how many times it is stored in the array and what are their respective array locations.

How can I add this output in my program.

Here's my code...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  int array[15]={28,3,16,4,3,16,5,8,4,12,5,4,8,21,40};
  int x=0;
  int done=0;
  int item;

  cout<<"Input an item to be searched:";
  cin>>item;

  while(done!=1&&x<15)
   {
    if(item==array[x])
      {
        cout<<"Found item"<<item<<" in the index of " <<x;
        done=1;
      }
  else
      {
       x++;
      }
   }
cout<<" item "<<item<<" is not found";

This should be the output:

Item to be searched: 4
number of occurence : 3
array locations : 3 8 11

Last edited on
Once the user inputs item, you will need a for loop to compare item against each of the values in array.
Seek inspiration from the reference documentation: http://www.cplusplus.com/reference/algorithm/count/

In order to list the locations in the end, they should be stored into a list (array/vector/list) in the loop and then print the list at the end.
The OP does have a loop (line 9), but there are a few problems with it.

1) When the first match is found, that will cause done to be set and the loop will exit. Therefore, no further matches will be detected. There is really no need for done, since you want to search the entire array rather than exiting on the first match.

2) You want to count the number of matches, but you have no match count variable.

3) Line 21 is going to get executed regardless of whether you found a match or not.
What you want here is an if statement:
21
22
23
24
25
 
  if (match_count == 0)
    cout << "No matches found" << endl;
  else
    cout << match_count << " matches found" << endl;
Topic archived. No new replies allowed.