Number never found

The number is never found. I'm not sure what the deal is here.

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
#include <iostream>
#include "Header1.h"
#include <iomanip>
using namespace std;


int main() {


	int numberChoice;
	bool which;
	listOfNumbers num;
	initialize(num);
	assign(num);
	print(num);
	cout << endl << "Pick a number to find..." << endl;
	cin >> numberChoice;
	numberChoice = choice(num, numberChoice);


	if (numberChoice == -1) {
		cout << "Number not found..." << endl;
	}
	else {
		cout << "Number Found!!!! : " << numberChoice;
	}

	return 0;
}

void initialize(listOfNumbers& p) {

	p.arrayLength = 60;
	for (int i = 0; i < p.arrayLength; i++) {
		p.array[i] = 0;
	}

}
void assign(listOfNumbers& p) {
	for (int i = 0; i < p.arrayLength; i++) {
		p.array[i] = i+1;
	}
}
void print(listOfNumbers& p) {
	for (int i = 0; i < p.arrayLength; i++) {

		if (i % 6 == 0) {
			cout << endl << endl;
		
			
		}
		cout << setw(4) << p.array[i] << "  ";
	}
}
int choice(listOfNumbers& p, int numberChoice) {

	int i;
	bool which = false;
	for (i = 0; i < p.arrayLength; i++) {
		p.array[i];
		if (p.array[i] == numberChoice) {
				which = true;
				break;
			}
			if (which == true) 
				return i;
			
			else 
				return -1;
			
		}

}
Last edited on
Your for loop that begins on line 59 will never repeat. This function will either return nothing, resulting in undefined behavior when you use the result it didn't return or return -1. There is no other possibility given the logic in the function.
Your choice function is faulty.

If the first if-condition is false, the function will immediately return -1 in the first iteration of the loop.

If the first if-condition happens to be true on the first iteration, then 'which' is assigned true, and the break statement that follows will break you out of the for-loop. Thus, the return statement on line 66 will never be executed.

Try this:

1
2
3
4
5
6
7
8
9
10
11
12
int choice(listOfNumbers& p, int numberChoice) {

	int i;
	for (i = 0; i < p.arrayLength; i++) {
	     if (p.array[i] == numberChoice) {
			return i;            // if number found, simply return index
	      }
         }
		
         return -1; // if we made it outside of the loop, number was never found, so return -1. 

}



Last edited on
I see. I've got to work on thinking logically. I seem to make logic mistakes more than syntax. I guess that's just natural to make these mistakes.
Thanks dudes!
Topic archived. No new replies allowed.