Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to check a given string is Palindrome or Not

C++ Code Example — String Programs

ADVERTISEMENT

WAP to check a given string is Palindrome or Not

Objective

Write a C++ program to check if a string is a Palindrome.

Algorithm / Approach

  1. Read a string into s1.
  2. Make a backup copy: s2 = s1.
  3. Reverse the original string: reverse(s1.begin(), s1.end()).
  4. Compare the modified original to the backup: if (s1 == s2).
  5. If they match, it is a palindrome.
main.cpp
#include<iostream>
#include< algorithm>
using namespace std;
int main() {
 string s1,s2;
 cout<<"Enter a string : ";
 getline(cin,s1);
 s2 = s1;
 reverse(s1.begin(),s1.end());
 if(s1==s2) {
  cout<<"String is Palindrome";
 }
 else {
  cout<<"String is not Palindrome";
 }
 return 0;
}

Expected Output

Enter a string : cprowess
String is not Palindrome

Explanation of the Program

  • A palindrome string reads identically forwards and backwards (e.g., "racecar").
  • By using the C++ standard library features we've already learned (string assignment, the reverse() algorithm, and the == operator), checking for a palindrome becomes a trivial 4-line task.

Complexity

Time Complexity O(n)
Space Complexity O(n)
ADVERTISEMENT