Array Search cout problem

I have the code pretty much done. The only problem I am having is that at Line 36 where I have the cout "Element not found" line with display 20 times multiple times if the number to be searched for is in more than one spot. I just want it to be displayed one time if the number cannot be 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
40
#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    int num_list[20];
    int y;


    cout << "Please provide 20 integer numbers" << endl;
    //Loop that obtains the numbers for the search
    for(int x = 0; x < 20; x++)
    {
        cout << "Enter number " << x << ":" << endl;
        //obtains the numbers for the average and stores
        //them in the array num_list
        cin >> num_list[x];
    }

    cout << "What number are you searching for?" << endl;
    cin >> y;


    //loop that compares all the numbers
    for(int x = 0; x < 20; x++)
    {
        //if it finds a match
        if(num_list[x] == y)
        {
            //it prints the location to the screen
            cout<<"Element found at index " << x << "." << endl;
        }
        else
        {
            cout << "Element not found." << endl;
        }

    }
}
take one
bool found = false;

in for loop.

 for(int x = 0; x < 20; x++)
{
        //if it finds a match
        if(num_list[x] == y)
        {
            //it prints the location to the screen
            cout<<"Element found at index " << x << "." << endl;
            found = true;
        }
}
if(!found)
{
          cout << "Element not found." << endl;
}
Last edited on
thanks for the response. That worked. I thought I had it after I posted. I moved the cout to outside the loop and that fixed it from repeating 20 times but it still displayed everytime. Thanks again for your help.
Topic archived. No new replies allowed.