Table of contents
1.
Introduction
2.
What is a Palindrome Number?
3.
C++ Palindrome Number Algorithm
4.
Code for Palindrome Program in C++
4.1.
C++
4.2.
Time Complexity
4.3.
Space Complexity
5.
Using reverse() Function in STL
5.1.
C++
6.
Checking Palindrome Number in C++ by Traversing the String
6.1.
C++
7.
Check Palindrome Number using Function
7.1.
C++
8.
Check Palindrome Number Using Two Pointers in C++
8.1.
Example
8.2.
C++
9.
Alternate Approaches for Palindrome Program.
9.1.
Naive Approach
9.1.1.
Algorithm 
9.1.2.
Implementation
9.2.
C++
9.2.1.
Time Complexity
9.2.2.
Space Complexity 
10.
Efficient Approach
10.1.
Algorithm
10.2.
Implementation
11.
C++
11.1.
Time Complexity 
11.2.
Space Complexity
12.
Applications of Palindrome 
13.
Frequently Asked Questions
13.1.
How do you program a palindrome?
13.2.
How do you check if a sentence is a palindrome in C++?
13.3.
What is palindrome in C examples?
14.
Conclusion
Last Updated: Dec 18, 2024
Easy

Palindrome Program in C++

Author Nitika
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

A palindrome is a word, number, phrase, or sequence of characters that reads the same forward and backward, ignoring spaces, punctuation, and capitalization. Examples include words like "radar" and "level" or numbers like 121 and 12321.

In programming, solving the problem of detecting palindromes is a common exercise that enhances understanding of string manipulation, loops, and control structures.

Palindrome Program in C++

What is a Palindrome Number?

Any number, word or sequence that remains unchanged when reversed is called a Palindrome. These numbers, words or lines are the same when read from the front and back.

For example, 404 is the same when read from the front and back.

Hence 404 is a palindrome number.

In technical terms, a palindrome number is one where the first and last digits are the same, the second and second last digits are the same, and so on.

This goes both ways for words and sequences as well.

Also read palindrome number in python.

C++ Palindrome Number Algorithm

Now that we know what a palindrome number is, we will move forward to check whether a number is a palindrome number or not.

The following is the algorithm for Palindrome Program in C++.

  • Take any string input from the user.
     
  • Copy the input into a temp variable.
     
  • Reverse the digits of the temp variable.
     
  • Compare the reversed string with the original string.
     
  • If they are the same, it is a palindrome. Otherwise, not a palindrome.

Code for Palindrome Program in C++

  • C++

C++

#include <iostream>
#include <string>


using namespace std;


int main()
{
   string str, temp;
   int i = 0, j;

   cout << "Enter a string to check for Palindrome: ";
   cin >> str;

   temp = str;
   
   j = str.length() - 1;

//Reversing the temp string.

   while (i < j)
   {
       swap(str[i], str[j]);
       i++;
       j--;
   }

   if (temp == str)
   {
       cout << "The string is a palindrome." << endl;
   }
   else
   {
       cout << "The string is not a palindrome." << endl;
   }

   return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output

output

Time Complexity

O(N)

The Time Complexity of the above code is O(N). For the reversal of the string, the loop has to iterate over half of the string, which takes O(N/2) time

Space Complexity

O(N)

The Space Complexity of the above code is O(N), as the two stored variables take up O(N) space.

The above example was a simple program for Palindrome numbers in C++ using if and while loops.

Further, we will come across different ways to implement Palindrome Program in C++ using various approaches.

Palindrome string

Using reverse() Function in STL

  • C++

C++

#include <iostream>
#include <string>
#include <algorithm>

bool isPalindrome(std::string str) {
std::string original = str;
std::reverse(str.begin(), str.end());
return original == str;
}

int main() {
std::string str;
std::cout << "Enter a string: ";
std::cin >> str;
if (isPalindrome(str)) {
std::cout << "The string is a palindrome." << std::endl;
} else {
std::cout << "The string is not a palindrome." << std::endl;
}
return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output:

output

Explanation

In this example, we checked if a string is a palindrome by reversing it using the reverse() function from the STL. The function first copies the original string, reverses the copy, and compares it with the original to determine if it's a palindrome.

Checking Palindrome Number in C++ by Traversing the String

  • C++

C++

#include <iostream>
#include <string>

bool isPalindrome(std::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() {
std::string str;
std::cout << "Enter a string: ";
std::cin >> str;
if (isPalindrome(str)) {
std::cout << "The string is a palindrome." << std::endl;
} else {
std::cout << "The string is not a palindrome." << std::endl;
}
return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output:

output

Explantion

In this example, we traversed a string from both ends towards the middle, comparing characters to determine if it's a palindrome. If any mismatch occurs, it returns false; otherwise, it returns true.

Check Palindrome Number using Function

We can also check a number if it is palindrome using the reverse and compare functions. These are built-in string manipulation functions in C++. Let us understand them with the help of an example:

  • C++

C++

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;



// Function to check Palindrome number

bool isPalindrome(int num) {
string numStr = to_string(num);
string reversedStr = numStr;

// Using reverse() function
reverse(reversedStr.begin(), reversedStr.end());
return numStr == reversedStr;
}

// Main Method

int main() {

// Taking inputs
int number;
cout << "Enter a number: ";
cin >> number;

// Calling the created function for checking the palindrome number

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

return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output

output

Check Palindrome Number Using Two Pointers in C++

The two-pointer technique is an efficient way to check if a number is a palindrome. It involves converting the number into a string and using two pointers to compare characters from the beginning and end of the string.

Example

  • C++

C++

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

bool isPalindrome(int num) {
string str = to_string(num); // Convert number to string
int left = 0, right = str.length() - 1;

while (left < right) {
if (str[left] != str[right]) {
return false; // Not a palindrome
}
left++; // Move the left pointer forward
right--; // Move the right pointer backward
}
return true; // It's a palindrome
}

int main() {
int num;
cout << "Enter a number: ";
cin >> num;

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

return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output:

Enter a number: 12321  

12321 is a palindrome.  

Alternate Approaches for Palindrome Program.

There are two alternative approaches for the Palindrome Program in C++.

Naive Approach

This approach is similar to the implementation which we have seen earlier. But in this approach, we are using the inbuilt reverse() function for reversing the string.

Algorithm 

  • Two strings, A and B, are made
     
  • String A is copied to string B and then reversed.
     
  • The contents of the string are Palindrome if they turn out to be the same.
     
  • The result is printed accordingly.

Implementation

  • C++

C++

#include <bits/stdc++.h>
#include <iostream>
#include <string>


using namespace std;

int main() {

string A;
cout << "Enter a string to check for Palindrome:";
cin >> A;

string B = A;

// Reverse the second string
reverse(B.begin(), B.end());

// Check if the original and reversed strings are equal
if (A == B) {
cout << "Palindrome.\n";
} else {
cout << "Not palindrome.\n";
}
return 0;
}
You can also try this code with Online C++ Compiler
Run Code

The #include <bits/stdc++.h> statement in the above example contains all the headers of the standard library. It is used to have all the necessary libraries at once rather than declaring them individually.

Output 

output

Time Complexity

O(N)

The Time complexity of the above code is O(N). As we are using the reverse function with a linear complexity and other conditional operations are of taking constant time.

 

Space Complexity 

O(N)

The Space Complexity of the above code is also O(N) as the two stored variables (A) & (B) take up O(N) space even upon reversal.

Efficient Approach

This approach involves the transversal of the string.

Algorithm

  • Declare a string A. 
     
  • If the string is empty then return true.
     
  • Else, iterate over [0, N/2], using for loop and the variable i.
     
  • Check if the character at (i and N-i-1) are not equal.
     
  • If they are not the same, it is not Palindrome; if str[i] is always equal to str[N-i-1], then it is a palindrome.
     
  • Print the result accordingly.

 

Implementation

  • C++

C++

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

bool isPalindrome(string str,int n)
{
if(n == 0)
{
return true;
}

// Checking if the string is a palindrome

for (int i = 0; i < str.length() / 2; i++) {

if (str[i] != str[str.length() - i - 1]) {

return false;
}
}

return true;
}

int main()
{
string str;
cout << "Enter a string to check for Palindrome: ";
cin >> str;

int n = str.length();
bool isPalin = isPalindrome(str,n);

if(isPalin)
{
cout<<"Palindrome.";
}
else
{
cout<<"Not Palindrome.";
}
return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output

output

Time Complexity 

O(N)

The loop only iterates over half of the string and performs a constant number of operations. Therefore, the time complexity of the code is linear with respect to the length of the input string.

Space Complexity

O(1)

The Space Complexity of the above code is O(1) as no other space is used for the execution of the code.

Also see, Application of Oops

Applications of Palindrome 

Palindromes have practical applications across various fields, including computer science, mathematics, and data processing. Here are some key applications:

1. Data Validation: Palindrome checks are used in error detection and data integrity validation, ensuring that specific sequences remain unchanged when reversed.

2. Text Processing: In natural language processing, palindrome detection helps analyze patterns in text, such as identifying symmetrical words or phrases.

3. Genomics and DNA Analysis: Palindromic sequences are crucial in DNA studies, where they play a role in genetic recognition sites and molecular structure analysis.

4. Cryptography: Palindromes are studied in cryptography for constructing secure codes and deciphering symmetric patterns in encrypted data.

5. Algorithm Design and Problem Solving: Palindrome problems are essential in algorithm design, helping develop efficient solutions for string manipulation, dynamic programming, and recursion.

6. Data Compression: Palindromic patterns in data can be leveraged for compression algorithms, reducing redundancy and storage requirements.

7. Puzzles and Games: Palindromes are a common feature in word games, puzzles, and brain teasers, adding a layer of challenge and creativity.

 

Must Read  C Program to Reverse a Number

Frequently Asked Questions

How do you program a palindrome?

To program a palindrome in C++, reverse the string and compare it with the original.

How do you check if a sentence is a palindrome in C++?

To check if a sentence is a palindrome in C++, remove spaces and punctuation, then apply the palindrome logic.

What is palindrome in C examples?

A palindrome in C examples checks if a string or number reads the same forwards and backward, like "radar" or 1221.

Conclusion

In this article, we extensively discussed the Palindrome Program in C++. Implementing a palindrome program in C++ provides insight into fundamental string manipulation and algorithmic concepts. Palindromes showcase symmetry and are valuable exercises for beginners to reinforce their understanding of string operations and logic flow in programming.

Live masterclass