Check String for Palindrome

Beginner

Introduction

In this lab, you will learn how to write C++ code to check whether a given string is a Palindrome or not. A palindrome is a type of word, phrase, or sequence of characters that reads the same way whether forwards or backward. For example, "level" is a Palindrome because it reads the same way forwards and backwards. In this lab, we will write a simple program that will take as input a string and checks whether it is a Palindrome or not.

Creating a New Project and File

Change the current directory to the project directory using the command:

cd project

Next, we will create a new C++ file inside this project folder using an editor like touch or Vim. In this lab, we will create a file named main.cpp using the command:

touch main.cpp

Writing C++ code to check for Palindrome

  • In our C++ program, we can use the string library to take input a string from the user and perform the palindrome check. Here is a simple program to achieve this:
#include <bits/stdc++.h>
using namespace std;
int main() {
    string str, output;
    cout << "Enter a string: ";
    cin >> str;
    int n = str.length();
    for (int i = 0; i < n / 2; i++) {
        if (str[i] != str[n - i - 1]) {
            output = "Given string is not a Palindrome";
            break;
        }
        else {
            output = "Given string is a Palindrome";
        }
    }
    cout << output << endl;
return 0;
}

Compiling and Running the code

  • Compile the code using the g++ compiler in the terminal using the following command:
g++ main.cpp -o main
  • After compiling the code successfully, we can now execute the program using the following command:
./main
  • The program will prompt us to enter a string. We can enter any string and the program will display whether it is a palindrome or not.

Final Code

Here is the complete code to check whether a given string is a Palindrome or not in C++:

#include <bits/stdc++.h>
using namespace std;
int main() {
    string str, output;
    cout << "Enter a string: ";
    cin >> str;
    int n = str.length();
    for (int i = 0; i < n / 2; i++) {
        if (str[i] != str[n - i - 1]) {
            output = "Given string is not a Palindrome";
            break;
        }
        else {
            output = "Given string is a Palindrome";
        }
    }
    cout << output << endl;
return 0;
}

Summary

In this lab, you have learned how to create a simple program in C++ that checks whether a given string is a Palindrome or not. You have learned how to use C++ string library to take input from the user and perform a palindromic check. We hope you now have a better understanding of the C++ programming language and can apply this knowledge to create more complex programs in the future.

Other Tutorials you may like