Closing Program Problem

I am trying to write a program to search for a number in an array through binary search but when I build and run the code and the user enters the number after the prompt and presses return nothing happens. When the user presses the return key again the computer produces a window that says the program (CodeBlocks) has stopped working and is searching for a solution. It then says that a problem caused the program to stop working and windows is going to close the program. This only happens when the search function in the function definition section (starting at line 39) is added.

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
#include <iostream>
#include <fstream>
#include <cstdlib>

const int MAX_NUMBER = 100;
using namespace std;

//Function declarations
void input(int a[], int size, int& number_used);
int search(const int a[], int number_used, int search_value);


int main()
{
    int a[MAX_NUMBER], number_used, search_value;
    input(a, MAX_NUMBER, number_used);
    search (a, number_used, search_value);

    cout << "Number not in array" << endl;

    return 0;
}

//Function definitions
void input(int a[], int size, int& number_used)
{
    using namespace std;
    ifstream in_stream;
    in_stream.open("Number.txt");
        if(in_stream.fail())
        {
            cout << "Error.";
            exit(1);
        }
        else
            cout << "Please enter a number to search in the array:" << endl;
            cin >> number_used;
}
int search(const int a[], int number_used, int search_value)
{

        int i = 0, j = number_used -1, mid, pos = -1;
        while(i <= j)
        {
            mid = a[(1 + 97)/2];
            if(a[mid] == search_value)
            {
                return mid;
            }
            else if(a[mid] < search_value)
            {
                i = mid + 1;
            }
            else
            {
                j = mid - 1;
            }

        }
        return pos; 

}
Last edited on
When you call search, you pass number to search for instead of size of array, and number to search for is uninitialized.
Also your array is not filled anywhere.
Topic archived. No new replies allowed.