Search code examples
c++palindrome

Wrong answer calls on palindrome


I coded palindrome program. I think this code is right especially is_palindrome procedure. But I don't know why this answers wrong.

Because when I input 2 1 1, return must be This is palindrome. But it answers the other.

#include <iostream>
using namespace std;

bool is_palindrome(int input[], int numOfSlots);

int main(void) {
    int n;
    cin >> n;
    int *input = new int[n]; // A dynamic array with n slots
    for (int i = 0; i < n; i++) {
        cin >> input[i];
    }

    if (is_palindrome(input, n) == true) {
        cout << "This is a palindrome.";
    }
    else {
        cout << "This is NOT a palindrome.";
    }
    return 0;
}

bool is_palindrome(int input[], int numOfSlots) {
    int i = 0;
    while (i < numOfSlots/2)
    {
        if (input[i] != input[numOfSlots-i])
            return false;
        i++;
    }
    return true;
}

Solution

  • You are going one past then end of the array in if (input[i] != input[numOfSlots-i]). When i == 0 then input[numOfSlots-i] becomes input[numOfSlots] which in this case is input[2]. Since the last valid index of input is 1 you are comparing against garbage. You should have

    if (input[i] != input[numOfSlots-i - 1])