I need a guidance to understand where my logic is not working. I need to write a recursive function that receives array A, and array B from a user input. The function is checking if the arrays are reversed. For example: A = {1, 4, 6, 7, 5, 3, 2}, B = {2, 3, 5, 7, 6, 4, 1} the function will return 1. If they are not reversed, the function will return 0. The size of the arrays is irrelevant as it's the same for both A and B. When I run my program, no matter what's the input, the result is 0, even if the input is correct(B is reversed of A).
int areReversed(int* A, int* B, int n)
{
if (n <= 0) return 1; // all elements have been compared and are equal
// Compare first element of array A and last element of array B
if (A[0] != B[n - 1])
return 0; // elements are not equal
// Recursively compare remaining elements of arrays A and B
return areReversed(A + 1, B - 1, n - 2);
}
This is my code so far. Would love to know what's the reason the function returns 0 all the time and where my logic fails. On paper it should work from what I see.
I played around a bit, and changed the recursion call to (A + 1, B, n - 1) Did a few tests and it appears to be working. Would love a second opinion on the change and see if it flawless or there's still some work to do. In the original code I decremented n too much so it skipped few elements of B, thus the comparison was wrong.