To check if input is a PALINDROME in C++

Palindrome Checking in C++

Let's break this question down first.

What is expected from us?

We are to see if any input given to us is a palindrome or not. Now we consider the input to be proper, which means no exception handling will be required just yet. Now we need to check if the given input is the same whether read from left to right or from right to left.

What is the logic?

The inputs can be either string or int, so let's just go with the string data type, since it can also deal with int-based data.

Now, we declare for loops, one will POINT to the first element and the SECOND will point to the last element.

Let us have a conditional increment of the for loops, this way, the complexity of the code reduces.

The algorithm!

If the first and last elements are the same, then move to the second and last second element.
If the second and last second elements are the same, then move to the third and last third elements.
Do this until the pointers cross over.
In any case, if the condition is not satisfied, then exit the loop since it's not a palindrome.
If the code is not exited, then the string is a palindrome.

Code!!!

#include<bits/stdc++.h>
using namespace std;
int main()
{
    string input;
    cin>>input;
    
    for(int i=0;i<input.length();)
    {
        for(int j=input.length()-1;j>=0;)
        {
            if(input[i]==input[j])
            {
                i++;
                j--;
            }
            else
            {
                cout<<"Not a palindrome"<<endl;
                exit(0);
            }
        }
    }
    cout<<"It is a palindrome"<<endl;
}



Hope this helps, let me know if you have any doubts, in the comments.

Comments