Search code examples
c++pointerspalindrome

check if sub-array is palindrome with pointers


I need to find the sub-arrays centered in the middle of the original array and check if it is palindrome. After that I need to print the start index -1 and end index of the array.

I tried to do it but the outcome is not what I expected. Can you point out any mistakes that I made?

#include <iostream>
using namespace std;

void print_sub_pals(int *nums,int length)
{

    for (int i = 0; i < (length / 2); ++i)
    {
        for (int j = length -1 ; j < (length/2); j--)
        {
            int start = *(nums + i);
            int end = *(nums + j);
            if ((start) == (end))
            {
                cout << start - 1 << endl;
                cout << end << endl;
            }
            else
            {
                cout << "-1" << endl;
            }
        }
    }
}



int main()
{
    int len = 7;
    int arr[7] = { 1, 2, 3, 4, 3, 6, 7 };
    print_sub_pals(arr, len);
}

Solution

  • I changed the second loop. Now at least it enters the loop, I think you still have to change it.

    void print_sub_pals(int *nums, int length)
    {
        //example: length is 7,
        //i = 0, goes up to 3
        for (int i = 0; i < (length / 2); ++i)
        {
            //j starts from 6, goes down, it stops when it's not less than 3
            //for (int j = length - 1; j < (length / 2); j--) {//never gets here} 
    
            //j starts from 6, goes down, it stops when it's less than 3
            for (int j = length - 1; j >= (length / 2); j--)
            {
                int start = *(nums + i);
                int end = *(nums + j);
                if ((start) == (end))
                {
                    cout << start - 1 << endl;
                    cout << end << endl;
                }
                else
                {
                    cout << "-1" << endl;
                }
            }
        }
    }