Recursive Function Always Returns False

Carson Barry

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.

Foxhound

You need to return the result of your recursive call inside your else clause.

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
    return isNumberInArray(anArray, first, (last - 1), targetNum);
  }

It will return true if the the first item you consult is what you're looking for, however, it will never check further calls of isNumberInArray(), as you never check that value. When the program eventually works it way back up to the first call, it'll enter if (first > last) and return false, when it should in fact be returning the value from isNumberInArray.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related