check if a string is palindrome cpp

#include <iostream>
#include <string>
using namespace std;

bool isPalindrome(const string& str) {
    int left = 0;
    int right = str.length() - 1;

    while (left < right) {
        if (str[left] != str[right]) {
            return false;
        }
        left++;
        right--;
    }
    return true;
}

int main() {
    string input;
    cout << "Enter a string: ";
    cin >> input;

    if (isPalindrome(input)) {
        cout << input << " is a palindrome." << endl;
    } else {
        cout << input << " is not a palindrome." << endl;
    }

    return 0;
}

Explanation:

  • #include <iostream> and #include <string>: These lines include necessary libraries for input-output operations and string manipulation.
  • using namespace std;: This line allows usage of elements in the std namespace without explicitly specifying it.
  • bool isPalindrome(const string& str): This function takes a constant reference to a string and checks if it's a palindrome. It returns a boolean value (true if the string is a palindrome, false otherwise).
  • int left = 0; and int right = str.length() - 1;: These variables left and right are initialized to the beginning and end of the string, respectively.
  • while (left < right) { ... }: This while loop iterates until the left pointer crosses the right pointer.
  • if (str[left] != str[right]) { return false; }: If characters at left and right positions are not equal, the function immediately returns false, indicating the string is not a palindrome.
  • left++; right--;: The left pointer is incremented, and the right pointer is decremented in each iteration to compare the next set of characters.
  • return true;: If the loop completes without finding any mismatch, the function returns true, indicating the string is a palindrome.
  • int main() { ... }: This is the main function where the user inputs a string.
  • cout << "Enter a string: "; cin >> input;: Asks the user to input a string, which is stored in the variable input.
  • if (isPalindrome(input)) { ... } else { ... }: Calls the isPalindrome function with the input string and prints whether it is a palindrome or not based on the returned boolean value.