Note: The string can also be reversed using reverse function.
Program to print length of string, print the string in reverse and check the string is palindrome or not
Take the input string from the user, calculate and print the length of the string. Reverse and print the string. Compare the reversed string with the original string and check if they are the same. If strings are the same print Palindrome else print not a palindrome. To know more about palindrome read this Palindrome Strings.
Code
#include<bits/stdc++.h>
using namespace std;
int main(){
cout<<"Enter a string "<<endl;
string s; //to store string
getline(cin, s); //reading the string
int l=s.length(); //length of string
cout<<"The Length of String is: "<<l<<endl; //print length
for(int i=l-1;i>=0;i--){ //printing the string in reverse
cout<<s[i];
}
cout<<endl;
int flag=0; //for true or false value
int j=l-1; //to hold alphabets from reverse
for(int i=0;i<l/2;i++){
if(s[i]!=s[j]){ //if any variable doesn't match set flag to 1 and exit the loop
flag=1;
break;
}
j--; //moving to next alphabet from reverse
}
if(flag==0){ //if 0 print palindrome
cout<<"Palindrome"<<endl;
}
else{ //if 1 print not a palindrome
cout<<"Not a Palindrome"<<endl;
}
return 0;
}
Output
Enter a string
Codingdemons
The Length of String is: 12
snomedgnidoC
Not a Palindrome
0 Comments