Extra 5% OFF Use Code: OL05
Free Shipping over ₹999

String is palindrome

In this example, we will check given string is palindrome or not

#include <iostream>
#include <bits/stdc++.h>
using namespace std;

void palindrome(string str){
    string str1 = str;

    reverse(str1.begin(),str1.end());

    if(str1 == str)
        cout<<"Is palindorme"<<endl;
    else
        cout<<"Not Palindrome"<<endl;
}

int main(){
    string str = "ABCDCB";
    palindrome(str);
    return 0;
}

Output:

Not Palindrome

Explanation:

Step1: palindrome Function

void palindrome(string str){
    string str1 = str;

    reverse(str1.begin(), str1.end());

    if(str1 == str)
        cout<<"Is palindorme"<<endl;
    else
        cout<<"Not Palindrome"<<endl;
}

Breakdown of the Function:

  • Input: The function takes a string str as input.
  • Copy the String: string str1 = str; creates a copy of the input string str and stores it in str1.
  • Reverse the Copy:
reverse(str1.begin(), str1.end());

This line uses the reverse() function from the <algorithm> library. The function takes two arguments:

  • str1.begin(): An iterator pointing to the first character of str1.
  • str1.end(): An iterator pointing just past the last character of str1. After this operation, str1 is the reversed version of str.

Check for Palindrome:

if(str1 == str)
    cout<<"Is palindorme"<<endl;
else
    cout<<"Not Palindrome"<<endl;

After reversing the string, the program checks if str1 (the reversed string) is equal to str (the original string):

  • If str1 == str, it means the original string reads the same forward and backward, so it’s a palindrome, and the message "Is palindorme" is printed (note: there’s a small typo here which we’ll correct).
  • If they are not equal, the message "Not Palindrome" is printed.

Step2: main() Function

int main(){
    string str = "ABCDCB";
    palindrome(str);
    return 0;
}
  • The string str is initialized with the value "ABCDCB".
  • The palindrome(str) function is called to check if this string is a palindrome.

    Leave a Reply

    Your email address will not be published.

    Need Help?