0

I started learning C++ not long ago, and am trying to write a recursive function that determines whether or not an integer number is a palindrome (i.e. 12421 should return true, while 123 should return false). I can do this iteratively with little problem, but the given task is to use recursion, and with a function that only takes a single input-- here named test. Alas, for this I am not allowed to modify the function to accept more inputs, or else it'd surely be easier.

This is the code I have so far, and I can't figure out why it isn't working. The method I am attempting here is to take the integer, find the length of it and the first and last digits, and then recursively put the test value back into the function with the first and last digits "removed" so as to keep comparing until I reach the base case (test==0). The temp variables are... rather awkward but I don't how else to use the value of the original input without modifying it.

When I run it in Visual Studio, it gives a message on the second line saying "Exception thrown at 0x002D0C99 in ispalindrome.exe: 0xC0000005: Access violation writing location 0x00600F3C." Why would this be the case? Any help would be greatly appreciated.

 bool is_palindrome(int test)
{
    int length = 1, firstDigit, lastDigit;
    int temp = test;
    int temp2 = test;
    int temp3 = test;
    while (temp > 0)
    {
        temp /= 10;
        length++;
    }
    
    while (temp2 >= 10)
    {
        temp2 /= 10;
    }
    firstDigit = temp2;
    lastDigit = temp3 % 10;

    if (test==0)
        return firstDigit == lastDigit;
    else
    {
        is_palindrome(test-(firstDigit*length)-lastDigit);
    }
}
Asta Lee
  • 35
  • 5
  • Your recursive function is causing a [stack overflow](https://stackoverflow.com/questions/15976333/stack-overflow-caused-by-recursive-function). Your function is not doing what you think it is doing. I would recommend using a debugger (or just printing the value of `test`) to see what's going on. – Rish Jul 18 '21 at 11:59
  • Some Tips: Especially think about `(test-(firstDigit*length)-lastDigit`. Your break condition is also worth thinking about it. `is_palindrom` returns a value but you don't in the else case. Think about the then case also. If test is null you can savely return `true`. In the else case you have to "AND" `firstDigit == lastDigit` with the result of the next recursion. – Peter Paul Kiefer Jul 18 '21 at 12:08
  • I got it working now, thank you for the advice Peter! – Asta Lee Jul 19 '21 at 03:14

0 Answers0