Search in array

I'm playing around a little bit with arrays. At the botten of the code I'm searching for a specific number that the user input. It works fine but it only shows the index for one even if their is more than one in the array. How can I fix so all the indexs are shown. And if we were to say that the user put in the number 7 and there are three 7:s in the array how can I get the output,
There are 3 of the specific number you entered.

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
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
#include <iomanip>
#include <ctime>
using namespace std;

using namespace std;

int main()
{
    const size_t SIZE = 600;
    int x[SIZE];
    int num;
    
    cout << " How many integers do you want to randomize (<=600): ";
    cin >> num;
    
    
    srand(time(NULL));
    for(size_t idx=0; idx < num; idx++)
        x[idx] = (rand() % 100 + 1);
    for(auto idx=0; idx < num; idx++)
    {
        cout << setw(5) << x[idx];
        if((idx+1)%10 == 0) 
            cout << endl;
    }
    
    int sum = 0;
    float average = 0;
    for(auto idx=0; idx < num; idx++)
        sum += x[idx];
    average = static_cast<float>(sum) / num;
    cout << " Average = " << average << endl << endl;
    
    int searchNumber;
    cout << "Enter a search number: ";
    cin >> searchNumber;
    size_t foundIdx = -1;
    for (auto i = 0; i < SIZE; i++)
        if (x[i] == searchNumber)
            foundIdx = i;
    
    cout << endl << endl;
    if(foundIdx != -1)
        cout << "Index for the found number is: " << foundIdx << endl;
    else
        cout << "The number is not in the array!" << endl;
    return 0;
    
    return 0;
    
}
Last edited on
I formatted the changes I made in bold:

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
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream>
#include <iomanip>
#include <ctime>
using namespace std;

using namespace std;

int main()
{
    const size_t SIZE = 600;
    int x[SIZE];
    int num;
    
    cout << " How many integers do you want to randomize (<=600): ";
    cin >> num;
    
    
    srand(time(NULL));
    for(size_t idx=0; idx < num; idx++)
        x[idx] = (rand() % 100 + 1);
    for(auto idx=0; idx < num; idx++)
    {
        cout << setw(5) << x[idx];
        if((idx+1)%10 == 0) 
            cout << endl;
    }
    
    int sum = 0;
    float average = 0;
    for(auto idx=0; idx < num; idx++)
        sum += x[idx];
    average = static_cast<float>(sum) / num;
    cout << " Average = " << average << endl << endl;
    
    int searchNumber;
    cout << "Enter a search number: ";
    cin >> searchNumber;
    size_t foundIdx = -1;
    for (auto i = 0; i < num; i++){
        if (x[i] == searchNumber){
            if(foundIdx == -1) cout << "Index for the found number is:";
            foundIdx = i;
	    cout << " " << foundIdx;
        }
    }

    cout << endl << endl;

    if(foundIdx == -1)
        cout << "The number is not in the array!" << endl;

    return 0;
}


Hope this helps.
You're declaring an array to hold 601 integers and, as in sample code below, only a few cells are filled and then searching the array gives spurious positives:
1
2
3
4
5
6
7
8
 How many integers do you want to randomize (<=600): 5
   68    8   70   10   18 Average = 34.8

Enter a search number: 3
Index for the found number is: 387 //spurious positive

Process returned 0 (0x0)   execution time : 9.764 s
Press any key to continue.


You can do 2 things here: (a) either set all array values to 0 at the start or (b) declare the array dynamically - the latter is better as the program doesn't use any more memory than it needs to. Also you're not capturing more than one finds in the array because there's no way to flash a find as it happens and so we're only getting the final result of the search once the entire array has been finished searching

Some other points:
1. better distributed random number generation tools are available under C++11: http://stackoverflow.com/questions/13445688/how-to-generate-a-random-number-in-c
2. idx is declared as size_t (line 19) and auto (lines 21, 30) - try and be consistent
3. go easy on the endl usage unless you really want to flush the stream buffer http://stackoverflow.com/questions/213907/c-stdendl-vs-n
4. for easier read and following program flow use braces after for() (line 20), if() (line 24), else() (line 46) etc even if the statments within the loops are one line only

Finally, taking all of these into a/c, here you go:
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <iostream>
#include <iomanip>
#include <random>

using namespace std;


int main()
{
    int*  x = nullptr;
    cout << " How many integers do you want to randomize: \n";
    int num;
    cin >> num;

    x = new int[num];

    std::mt19937 rng;
    rng.seed(std::random_device()());
    std::uniform_int_distribution<std::mt19937::result_type> dist100(1,100);

    for(auto idx=0; idx < num; idx++)
    {
        x[idx] = dist100(rng);
    }

    for(auto idx=0; idx < num; idx++)
    {
        cout << setw(5) << x[idx];
        if((idx+1)%10 == 0)
        {
             cout << "\n";
        }
    }
    int sum = 0;
    float average = 0;
    for(auto idx=0; idx < num; idx++)
    {
        sum += x[idx];
    }

    average = static_cast<float>(sum) / num;
    cout << " \nAverage = " << average << "\n";

    cout << "Enter a search number: ";
    int searchNumber;
    cin >> searchNumber;

    bool match = false;
    for (auto i = 0; i < num; i++)
    {
        if (x[i] == searchNumber)
        {
            cout << "Number found at array cell: " << i << "\n";
            match = true;
        }
    }
    if(match == false)
    {
        cout << "The number is not in the array!\n";
    }

    delete x;
}
Thank you both! And thanks for all the tips @gunnerfunner!
@Gunnerfunner can you explain more about the endl, don't understands what the link mean with flushing the output buffer.
1
2
3
std::cout << std::endl;
//is equivalent to
std::cout << '\n' << std::flush;


So endl, in addition to placing the newline character, also flushes the output buffer. A buffer is a block of memory used as an intermediate, temporary storage facility for the transfer of information from a device (e.g. keyboard) to a program or from a program to a device (e.g console).
For small programs it may make no / not much performance difference but as the following link shows endl does slow programs down and in a large program this can have a considerable impact: http://stackoverflow.com/questions/1924530/mixing-cout-and-printf-for-faster-output/1926432#1926432
Regarding flush/endl with file output.

Normally I would avoid using endl when outputting data to a file, as there is no benefit over a simple '\n' and it does make it run more slowly.

However, in some circumstances there may be some long-running process which could run for an extended time, and which periodically outputs a status message to a log file. Here, I specifically would want to flush the output buffer after each message, otherwise it is possible that the log file could appear completely empty until the program finishes many hours later (the buffer is automatically flushed when the file is closed).
Topic archived. No new replies allowed.