My recursive program does not return true when it reaches the specified target, even when it looks like it should. It simply returns false, then terminates, and I can't figure out why.
I've tried to rearrange the order of the If/Else statements in every possible way, I've attempted to debug it using cout, and it looks like it should return true, but it doesn't.
#include <iostream> using namespace std; bool isNumberInArray(const int anArray[], int first, int last, int targetNum) { if (first > last) { //if last number is less than the first number to be searched return false; //Returns false if the size of the array to be searched is less than the first element of the array } if (anArray[last] == targetNum) { //if number at "last" position is equal to the target return true; //Returns true if the target is found at the last position } else { //run again, with last = last - 1 cout << "searching for " << targetNum << "; ran else; position " << last << " value " << anArray[last] << "\n"; //previous line used for testing purposes isNumberInArray(anArray, first, (last - 1), targetNum); } } int main() { int numberArray[10] = {1, 2, 3, 11, 5, 6, 7, 8, 9, 10}; if (isNumberInArray(numberArray, 0, 9, 11t)) cout << "True\n"; else cout << "False\n"; return 0; } The program should realistically return "true" when the value of last reaches the position that targetNum is located at, but instead it always returns false, even if it is true, and I can't figure out why. The cout statements that I placed within the function even stop when the program reaches the targetNum, but it still returns false:
searching for 11; ran else; position 9 value 10
searching for 11; ran else; position 8 value 9
searching for 11; ran else; position 7 value 8
searching for 11; ran else; position 6 value 7
searching for 11; ran else; position 5 value 6
searching for 11; ran else; position 4 value 5
False
11 is at position 3.
returnin the finalelseofisNumberInArray.isNumberInArrayrecursively, but you don't actually consult the return value of that call. In fact, your program exhibits undefined behavior, by way of reaching the end of a non-voidfunction without encountering areturnstatement.