Starting out with C++ 7th edition- chapter 8 programming challenges #1

Hi,

I'm trying to do challenge #1 from the programming challenges in chapter 8
the code complies but it's giving me some weird thing

like this: Thread 1: EXC_BAD_ACCESS (code=1, address=0x7fff5fc84000) on line # 43 of code

By the way I'm using Xcode

so I would like to know what is wrong with it. Thanks.


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>

using std::cout;
using std::cin;
using std::endl;

int main(){
    
    // The linear search function
    int searchlist( const int[], int, int );
    
    int userInput;   // The number that the user is going to type in
    const int size = 18;
    int listofnumber[size] = { 5658845, 4520125, 7895122, 8777541, 8451277, 1302850,
                               8080152, 4562555, 5552012, 5050552, 7825877, 1250255,
                               1005231, 6545231, 3852085, 7576651, 7881200, 4581002 };
    int results;
    
    results = searchlist( listofnumber, size, userInput);
    
    // ASK the user for input (to look it up on the list)
    cout << "Enter a number you would like to look up: ";
    cin >> userInput;
    
    cout <<"The number you enterd is in array: " << results << endl;
    
    
    return 0;
}

//#######################################################################

int searchlist( const int list[], int numElem, int value){
    
    int index = 0;
    int position = -1;
    bool found = false;
    
    
    while (position <= numElem && !found) {
        
        if (list[index] == value) {
            found = true;
            position = index;
            
        }
        index++;
        
    }
    
    return position;
}
Last edited on
You should have it get the user input, before sending data to the method.
1
2
3
4
5
6
7
8
9
10
 

    int results;
        // ASK the user for input (to look it up on the list)
    cout << "Enter a number you would like to look up: ";
    cin >> userInput;
    results = searchlist( listofnumber, size, userInput);
    

Last edited on
That worked thanks!.
Topic archived. No new replies allowed.