Introduction
In this lab, you will learn how to write a C++ program that checks whether a given string is a palindrome or not. A palindrome is a string that is the same as its reverse. To check for a palindrome, we will reverse the given string and compare it with the original. If both the strings are the same, the given string is a palindrome, else, it is not.
Include Required Libraries and Define the main() Function
First, we will include the required libraries and define the main() function.
#include <iostream>
#include <string.h>
using namespace std;
int main() {
// code goes here
return 0;
}
Get Input String from the User
Next, we will get the input string from the user and store it in an array of characters.
char inputStr[100];
cout << "Enter a string: ";
cin >> inputStr;
Get the Length of the Input String
We will calculate the length of the input string using the strlen() function.
int strLength = strlen(inputStr);
Create an Array for Reverse String
Next, we will create an array for the reverse string.
char reverseStr[strLength];
Reverse the Input String
We will now reverse the input string and store it in the newly created array for the reverse string.
for(int i = 0; i < strLength; i++) {
reverseStr[i] = inputStr[strLength - 1 - i];
}
Compare Original and Reverse Strings
Finally, we will compare the original and reverse strings to check whether the input string is a palindrome or not.
if(strcmp(inputStr, reverseStr) == 0) {
cout << inputStr << " is a palindrome." << endl;
} else {
cout << inputStr << " is not a palindrome." << endl;
}
Full Code
#include <iostream>
#include <string.h>
using namespace std;
int main() {
char inputStr[100];
cout << "Enter a string: ";
cin >> inputStr;
int strLength = strlen(inputStr);
char reverseStr[strLength];
for(int i = 0; i < strLength; i++) {
reverseStr[i] = inputStr[strLength - 1 - i];
}
if(strcmp(inputStr, reverseStr) == 0) {
cout << inputStr << " is a palindrome." << endl;
} else {
cout << inputStr << " is not a palindrome." << endl;
}
return 0;
}
Summary
In this lab, you learned how to write a C++ program that checks whether a given string is a palindrome or not. You can now use this program to quickly check if any string is a palindrome or not.



