C++ Program to Check Whether String is Palindrome


This is a C++ Program to Find if a String is Palindrome.

Problem Description

The program checks if a string is a palindrome or not. A palindrome is a word or a string that reads the same backward and forward.

Problem Solution

1. The program takes a string and stores it.
2. The string is copied into another string from backwards.
3. If both the strings are equal, then the entered string is a palindrome.
4. Else it is not.
5. The result is printed.
6. Exit.

C++ Program/Source code

Here is the source code of C++ Program to Find if a String is Palindrome. The program output is shown below.

  1. #include <iostream>
  2. #include <string.h>
  3. using namespace std;
  4. int main()
  5. {
  6.     char str1[20], str2[20];
  7.     int i, j, len = 0, flag = 0;
  8.     cout << "Enter the string : ";
  9.     gets(str1);
  10.     len = strlen(str1) - 1;
  11.     for (i = len, j = 0; i >= 0 ; i--, j++)
  12.         str2[j] = str1[i];
  13.     if (strcmp(str1, str2))
  14.         flag = 1;
  15.     if (flag == 1)
  16.         cout << str1 << " is not a palindrome";
  17.     else
  18.         cout << str1 << " is a palindrome";
  19.     return 0;
  20. }
Program Explanation

1. The user is asked to enter a string and it is stored in the character variable ‘str1’.
2. The length of str1 is stored in ‘len’ using the string function strlen().
3. Using a for loop, str1 is copied into another variable ‘str2’ from backwards.
4. Both the strings str1 and str2 are compared using string function strcmp().
5. A temporary variable flag is used.
6. If str1 is equal to str2, then the entered string is a palindrome, else not.
7. The result is then printed.

Runtime Test Cases
Case 1 :
Enter the string : nun
nun is a palindrome
Case 2 :
Enter the string : fast                                                                                                        
fast is not a palindrome
Case 3 :
Enter the string : 121                                                                                                         
121 is a palindrome

Sanfoundry Global Education & Learning Series – C++ Programs.

To practice all C++ programs, here is complete set of 1000+ C++ Programming examples.


Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn