C++ Programming

Write a program in C++ to check whether a given string is a palindrome or not using the pointer method.

Method 1

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

//Function to check if a string is palindrome
bool isPalindrome(const char* str)
{
//Pointer at the start of the string
const char* left = str; 
//Pointer at the end of the string
const char* right = str + strlen(str) - 1; 
while (left < right) 
{
if (*left != *right) 
{
return false; // Mismatch found
}
left++;  // Move left pointer forward
right--; // Move right pointer backward
}
//Return true if we get palindrome
return true; 
}

int main() {

char str[200]; 
cout << "Enter any string: ";
cin.getline(str, 200); 

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

Output 1

Enter any string: radar
radar is a palindrome

Output 2

Enter any string: hello
hellois not a palindrome.

Method 2

#include <iostream>
#include <string>

using namespace std;

//Function to check if the given string is palindrome or not
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 str;
cout << "Enter any string: ";
getline(cin, str);

if (isPalindrome(str)) 
{
cout << str << " is a palindrome" << endl;
} else {
cout << str << " is not a palindrome" << endl;
}
return 0;
}

Output 1

Enter any string: radar
radar is a palindrome

Output 2

Enter any string: hello
hello is not a palindrome
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments