Trying to get my program to run forever until user hits 0

"Perform a BINARY search to locate the number. If found display "Number %d Found at Position %d". Where the first %d is the number the user is searching for and the second %d is the location in the SORTED ARRAY. Else display "Number %d Not Found", where you will put the number the user is searching for in place of %d. You can use either printf() or cout.

Your search should run until the user enters '0'. Therefore, the search section should be in a loop."

What do i insert to make the program run forever until hitting zero? As of now if they hit "0" the program closes and displays the prompt "You have chosen to exit the program", but when i try to enter a number to search the array it just says the number is in the element i typed in? I know i need to implement "Number &d found at position &d... number not found... keep searching, but i don't know how to do that.


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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>


using namespace std;

// function prototypes
int binarySearch(int array[], int size, int value);
void selectionSort(int array[], int size);
void swap(int &, int&);

const int SIZE = 200;

int main()
{
    // prompt user to enter file name. also display if it exists or not
    ifstream inputFile; // gives access to file
    string name, filename;
    const int ARRAY_SIZE = 200;
    int numbers[ARRAY_SIZE];
    int count = 0;
    int number;


    // Get file name from the user
    cout << "Enter the file name: ";
    cin >> filename;

    // Open the file
    inputFile.open(filename.c_str());

    // If the file opened successfully, process it
    if (inputFile)
    {
        // Read the numbers from the file and display them.
        while (count < ARRAY_SIZE && inputFile >> numbers[count])
        count++;
        {
            cout << number << endl;
        }

        // Close the file
        inputFile.close();
    }
    else
    {
        // display an error message if the file was not found
        cout << "Error opening the file.\n";
        inputFile.close();

    }

       // display the numbers read
       cout << "The numbers are: ";
       for (count = 0; count < ARRAY_SIZE; count++)
        cout << numbers[count] << " ";
       cout << endl;

      // prompt user to search for the number
      cout <<  ("Enter number to search for or 0 quit: ");
      cin >> number;



      // search for the number
      int binarySearch(const int array[], int size, int value);

      //Searches for # in the array
      if(number == 0)
        cout << "You have chosen to exit the program.\n";
      else{
        cout << "That number was found at element " << number;
        cout << " in the array\n";
      }

   return 0;
}

    // sort the array using selection sort
    void selectionSort(int array[], int size) // function used outside of main
    {

        int minIndex, minValue; // declaration

        for(int start = 0; start < (size - 1); start++) // search begins from one element below the actual starting point
         {
            minIndex = start;
            minValue = array[start];
            for(int index = start + 1; index < size; index++) // incremented by one value at a time
            {
                if(array[index] < minValue)
                {
                    minValue = array[index]; // locates element in position 0
                    minIndex = index;
                }
            }
            swap(array[minIndex], array[start]);

         }

        }

// swap function
    void swap(int &a, int &b)
    {
        int temp = a;
        a = b;
        b = temp;
    }


    // perform a binary search to locate the number, If found display
    int binarySearch(const int array[], int size, int value) //
    {

        int first = 0, // First array element
            last = size - 1, // Last array element
            middle, // Mid point of search
            position = -1; // Position of search value
        bool found = false; // Flag

        while(!found && first <= last)
        {
            middle = (first + last) / 2; // Calculate mid point
            if(array[middle] == value)  // If value is found at mid
            {
                found = true;
                position = middle;
            }
            else if(array[middle] > value)  // If value is in lower half
                last = middle - 1;
            else
                first = middle + 1; // If value is in upper half
        }
        return position;
    }


1
2
3
4
5
6
7
8
while (cin>>number and number not_eq 0){
	int position = binary_search(numbers, count, number);
	if (position not_eq -1)
		cout << "That number was found at position " << position << " in the array\n";
	else
		cout << "Not found\n";
}
cout << "You have chosen to exit the program.\n";



I wonder how far you may get, good luck.
Hello FanOfThe49ers,

I do not always remember what IDE/compiler is used bu who, and I do not recall if you have mentioned what you are using. The other problem is what C++ standard are you using with the compiles? is it pre2011, 2011 or newer standard?

Looking at your code:
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
const int SIZE = 200;  // <--- Defined, but never used.

int main()
{
    const int ARRAY_SIZE = 200;
    ifstream inputFile; // gives access to file.  Defines the file stream variable used.
    string name, filename;
    int numbers[ARRAY_SIZE];  // <--- Needs initialized.
    int count = 0;
    int number;  // <--- Needs initialized.

    // prompt user to enter file name. also display if it exists or not
    // Get file name from the user
    cout << "Enter the file name: ";
    cin >> filename;

    // Open the file
    inputFile.open(filename.c_str());  // <--- ".c_str()" not needed from the 2011 standards on.

    // If the file opened successfully, process it
    if (inputFile)
    {
        // Read the numbers from the file and display them.
        while (count < ARRAY_SIZE && inputFile >> numbers[count])
            count++;
        {
            cout << number << endl;
        }

        // Close the file
        inputFile.close();
    }
    else
    {
        // display an error message if the file was not found
        cout << "\n     Error opening the file.\n\n";
        inputFile.close();
    }

    // display the numbers read
    cout << "The numbers are:\n";

    for (count = 0; count < ARRAY_SIZE; count++)
        cout << numbers[count] << " ";
    cout << endl;


And when I run this much I get:

Enter the file name: a.txt

     Error opening the file.

The numbers are:
-858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460



If I initialize the array it looks like this:

Enter the file name: a.txt

     Error opening the file.

The numbers are:
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0


In the console window the line wraps, so it looks a little different.

When you get to line 14 there is no way to know what file name to enter. You could do something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
    std::string fileNames[]
    {
        "File1.txt",
        "File2.txt",
        "File3.txt"
    };

    std::cout << "\nFile names available:\n";

    for (int idx = 0; idx < sizeof(fileNames)/sizeof(fileNames[0]); idx++)
    {
        std::cout << ' ' << fileNames[idx] << '\n';
    }

    // prompt user to enter file name. also display if it exists or not
    // Get file name from the user
    cout << "\nEnter the file name: ";
    cin >> filename;


The output would be:

File names available:
 File1.txt
 File2.txt
 File3.txt

Enter the file name:



Line 18. From C++11 standards on the ".c_str()" is not needed/ A "std::string" will work fine.

From line 21 - 38 they are backwards. Not the best idea to run your program off an if else statement. In the else statement you print an error message then close a file stream that is not open before you continue on with the program having no file to read and nothing to work with.

I most often see something more along these lines:
1
2
3
4
5
6
7
8
inputFile.open(filename);

if (!inputFile)
{
    cout << "\n     Error opening the file.\n\n";

    return 1;
}

Then this would be followed by the while loop:
1
2
3
4
5
6
7
8
9
10
// Read the numbers from the file and display them.
while (count < ARRAY_SIZE && inputFile >> numbers[count])
    count++;

{
    cout << number << endl;
}

// Close the file
inputFile.close();

I added the extra blank line to show that lines 5 - 7 are not part of the while loop. Also "number as an uninitialized variable caused an error trying to use it before it receives a proper value.

Once I created an input file, not saying my input is like yours, and made the changes it worked until I called the "binarySearch" Which returned a value and not the position in the array that is needed. I have that to check into next.

Andy
I tried your recommendation int position = binary_search(numbers, count, number);
and it says undefined reference to binary search(int*, int, int)??
I'm very confused about most of the stuff you wrote Andy, when i run my program it runs fine, and i'm not sure what version it is. I feel like my teacher skipped really helping us understand algorithms so i've been trying trying to get a ton of help as this is due tomorrow, and i don't have time to actually practice understanding yet. : this is my output and teacher never prompted us to display the file names . I don't watch to change much because it's working and i'm getting way to confused changing half my program
Enter the file name: numbers.txt
0
The numbers are: 156 106 109 3 124 12 52 33 27 66 164 79 200 60 85 82 35 44 180 133 97 117 152 174 1 69 24 118 112 127 129 65 126 104 175 197 63 120 36 151 172 19 113 47 38 132 39 74 56 185 137 67 123 168 21 95 182 2 116 155 107 165 68 7 30 192 139 18 26 16 199 170 110 6 138 121 64 51 163 57 23 80 84 4 13 54 122 20 119 194 53 176 187 40 25 76 58 130 167 115 183 111 193 190 140 22 134 15 166 198 131 29 61 114 90 77 96 73 32 45 94 147 42 71 78 8 135 195 159 46 161 14 41 142 153 178 105 136 11 43 62 93 181 9 75 37 49 146 55 87 143 92 89 86 189 5 141 186 144 169 81 158 150 148 83 17 179 28 103 48 177 10 72 128 125 108 171 173 34 31 154 149 145 91 101 100 188 184 98 157 191 102 88 196 162 70 50 59 160 99
Enter number to search for or 0 quit:


If i hit zero i get my prompt message & it closes it. I just want to implement a statement to continue searching until i hit 0 and so that it will tell me : If found display "Number %d Found at Position %d". Where the first %d is the number the user is searching for and the second %d is the location in the SORTED ARRAY. Else display "Number %d Not Found", where you will put the number the user is searching for in place of %d. You can use either printf() or cout.
Last edited on
the output of numbers is displayed correctly in my program in a box shape, idk why it displayed incorrectly on here
I took your recommendation on the available files as it does make a lot of sense
I'll say it again so maybe it's more clear, from what i have already all i need it to do is:
1) keep searching numbers, and locating the position in the array until user hits zero.
2) Display number not found if it's NOT in the array, and continue searching since they didn't hit zero.
3) Thanks a ton for the help i'm very new to this and don't have a lot of practice so i get lost easily.
Also even if i hit an incorrect file name it still displays the numbers unsorted in a weird pattern, i'm unsure why.
I adjusted my file by adding:
1
2
3
4
5
6
7
8
 inputFile.open(filename);

if (!inputFile)
{
    cout << "\n     Error opening the file.\n\n";

    return 1;
}  


&
1
2
3
4
5
6
7
8
9
  while (count < ARRAY_SIZE && inputFile >> numbers[count])
    count++;

{
    cout << number << endl;
}

// Close the file
inputFile.close();  




But now even if i type the correct filename it doesn't display the numbers lol, is my programming not for me or something
Last edited on
Hello FanOfThe49ers,

My apologies. Sometimes I forget that in the utopia of school no one does anything wrong.

The part about listing the available file names is optional. You do not have to use it.

when i run my program it runs fine

This may be true for you, but not always true for others.

Just because your code may seem to work does not mean that it is correct.

In your original code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
if (inputFile)
{
    // Read the numbers from the file and display them.
    while (count < ARRAY_SIZE && inputFile >> numbers[count])
        count++;
    {
        cout << number << endl;
    }

    // Close the file
    inputFile.close();
}
else
{
    // display an error message if the file was not found
    cout << "Error opening the file.\n";
    inputFile.close();
}

Lines 6, 7 and 8 the {}s do not make this part of the while loop. The is a separate block. The while loop ends when it finds the first (;).

The else statement prints an error message, providing that the if statement is false, closed a file stream that is not open and continues on with the program. This is not what you want.

If you open the file and the if condition is true the while loop properly reads the file and the else is bypassed and your program continues.

Next you display the numbers before they are sorted. That is fine, but not what the "binarySearch()" need to work with.

The "binarySearch()" needs a sorted array to work properly. If you sort the array before you call the "binarySearch()" both functions work fine.

Your code int binarySearch(const int array[], int size, int value); your line 68 is a very nice prototype or function definition, but you already have both. What it is not is a function call. The function call should be position = binarySearch(numbers, count, number);.

"position" captures the return value of the function and all you need to call the function is the names that were created in "main". Changing the names at the function is OK.

When you run your for loop:
1
2
3
4
5
6
for (int idx = 0; idx < count; idx++)
{
    cout << numbers[idx] << " ";
}

cout << endl;

This will print 1 vary long line, but your console window will wrap the line when it reaches the right side. When posting that output here it shows up as 1 vaer long line because that is what it is. It might wrap the line is you omit the output tag. Not sure.

At the end of "main" I did make this change:
1
2
3
4
5
6
7
8
9
10
11
if (number == 0)
    cout << "\nYou have chosen to exit the program.\n";
else if (position > 0)
{
    cout << "\nThat number was found at element " << position;
    cout << " in the array\n";
}
else
{
    std::cout << "\n     Number not found.\n";
}

The problem here is that if number == 0 you are checking for this after you have sorted and searched for (0). This check needs to be done after you enter the number to search for. Then the "else if" would change to just an "if" statement.

Your are correct in saying that your code works, just not working in the best way.

If you can get what you have working better at least 1 time then you can add ne555's idea of the while loop. By then it should be easier to make that change.

Andy
I re-wrote my entire program and i'm doing one thing at a time so i'm not confused and can actually learn better, my next big question is why when i try to run the program & display the sorted values they all display as 0's?

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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// function prototypes
int binarySearch(const int [], int, int);
void selectionSort(int[], int);
void swap(int &, int &);

const int SIZE = 200;








int main()
{
    const int ARRAY_SIZE = 200; // Array size
    int numbers[ARRAY_SIZE];    // array with 200 elements
    int count = 0;              // Loop counter variable
    ifstream inputFile;         // Input file
    string name, filename;
    int number;
    int values[ARRAY_SIZE] = {};


    std::string fileNames[]
    {
        "numbers.txt",
        "File2.txt",
        "File3.txt"
    };

    std::cout << "\nFile names available:\n";

    for (int idx = 0; idx < sizeof(fileNames)/sizeof(fileNames[0]); idx++)
    {
        std::cout << ' ' << fileNames[idx] << '\n';
    }

    // prompt user to enter file name. also display if it exists or not
    // Get file name from the user
    cout << "\nEnter the file name: ";
    cin >> filename;

    // open the file
    inputFile.open(filename);

    if (inputFile)
    {
        // Read the numbers from the file and display them.
        while (count < ARRAY_SIZE && inputFile >> numbers[count])
        count ++;
        {
            cout << number << endl;
        }

        // close the file.
        inputFile.close();
    }
    else
    {
        // Display an error message.
        cout << "Error opening the file.\n";
    }

    // display the numbers read:
    cout << "The numbers are: ";
    for (count = 0; count < ARRAY_SIZE; count++)
    cout << numbers[count] << " ";
    cout << endl;


    // sort the array
    selectionSort(values, ARRAY_SIZE);

    // Display the sorted array
    cout << "The sorted values:\n";
   for (auto element : values)
      cout << element << " ";
   cout << endl;


    return 0;
}
for some reason, you've decided to create two arrays: `numbers' and `values'
your read the content of your file into `numbers', but sort and display `values'
in line 23 you do int values[array_size] = {}; initialiazing all its elements to 0, so when you display them they are all 0

also, ¿why did you exclude the preamble (includes and using statement) and the functions definitions from your code snip?
Consider:

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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#include <iostream>
#include <fstream>
#include <string>
#include <utility>

int binarySearch(const int[], int, int);
void selectionSort(int[], int);

const int ARRAY_SIZE = 200; // Array size

int main()
{
	int numbers[ARRAY_SIZE] {};    // array with 200 elements
	int count = 0;              // number read
	std::ifstream inputFile;         // Input file
	std::string filename;

	const std::string fileNames[] {"numbers.txt", "File2.txt", "File3.txt" };

	std::cout << "\nFile names available:\n";

	for (const auto& fn : fileNames)
		std::cout << ' ' << fn << '\n';

	// prompt user to enter file name. also display if it exists or not
	// Get file name from the user
	std::cout << "\nEnter the file name: ";
	std::cin >> filename;

	// open the file
	inputFile.open(filename);

	if (inputFile)
	{
		// Read the numbers from the file and display them.
		while (count < ARRAY_SIZE && inputFile >> numbers[count])
			count++;

		// close the file.
		inputFile.close();
	} else
	{
		// Display an error message.
		std::cout << "Error opening the file.\n";
		return 1;
	}

	// display the numbers read:
	std::cout << "The numbers are: ";
	for (int c = 0; c < count; ++c)
		std::cout << numbers[c] << " ";

	std::cout << std::endl;

	// sort the array
	selectionSort(numbers, count);

	// Display the sorted array
	std::cout << "The sorted values:\n";
	for (int c = 0; c < count; ++c)
		std::cout << numbers[c] << " ";

	std::cout << std::endl;

	int num = 0;

	do {
		std::cout << "Enter number to find: ";
		std::cin >> num;

		if (num) {
			const int fnd = binarySearch(numbers, count, num);

			std::cout << "Number " << num;

			if (fnd >= 0)
				std::cout << " found at position " << fnd << std::endl;
			else
				std::cout << " not found\n";
		}
	} while (num);
}

// sort the array using selection sort
void selectionSort(int array[], int size) // function used outside of main
{
	int minIndex = 0, minValue = 0; // declaration

	for (int start = 0; start < (size - 1); start++) // search begins from one element below the actual starting point
	{
		minIndex = start;
		minValue = array[start];

		for (int index = start + 1; index < size; index++) // incremented by one value at a time
		{
			if (array[index] < minValue)
			{
				minValue = array[index]; // locates element in position 0
				minIndex = index;
			}
		}
		std::swap(array[minIndex], array[start]);
	}
}

// perform a binary search to locate the number, If found display
int binarySearch(const int array[], int size, int value) //
{

	int first = 0, // First array element
		last = size - 1, // Last array element
		middle, // Mid point of search
		position = -1; // Position of search value
	bool found = false; // Flag

	while (!found && first <= last)
	{
		middle = (first + last) / 2; // Calculate mid point
		if (array[middle] == value)  // If value is found at mid
		{
			found = true;
			position = middle;
		} else if (array[middle] > value)  // If value is in lower half
			last = middle - 1;
		else
			first = middle + 1; // If value is in upper half
	}
	return position;
}

Topic archived. No new replies allowed.