✅ Palindrome Check for Strings in C++
Checking whether a string is a palindrome is a common question asked in programming interviews, exams, and competitive coding platforms. A palindrome string reads the same forward and backward (e.g., "madam"
, "racecar"
, "level"
).
This example helps BSc CS students understand how to work with strings and loops in C++ effectively.
📘 What You'll Learn
-
How to reverse a string
-
Compare strings in C++
-
Understand character-wise logic
-
Write clean and optimized code
📄 Code: C++ Palindrome Check for Strings
#include <iostream>
#include <string>
using namespace std;
int main() {
string input, reversed = "";
cout << "Enter a string: ";
cin >> input;
// Reversing the string
for (int i = input.length() - 1; i >= 0; i--) {
reversed += input[i];
}
// Comparing original and reversed
if (input == reversed) {
cout << input << " is a Palindrome.";
} else {
cout << input << " is not a Palindrome.";
}
return 0;
}
✅ Sample Output
Enter a string: madam
madam is a Palindrome.
📘 Explanation
-
We take the input string from the user.
-
Reverse it using a
for
loop. -
Then, compare it with the original string.
-
If both match, it’s a palindrome!
Post a Comment