A palindrome is a word, phrase, number, or any sequence of characters that reads the same forward and backward. Examples include “radar,” “madam,” “level,” and “racecar.”
In this article, we’ll explore how to check whether a given string is a palindrome using a simple algorithm and an efficient program.
A string is considered a palindrome if:
To determine whether a string is a palindrome, follow these steps:
# Function to check if a string is a palindrome
def is_palindrome(s):
return s == s[::-1] # Reverse and compare
# Input from the user
string = input("Enter a string: ")
# Check if palindrome
if is_palindrome(string):
print("The given string is a palindrome.")
else:
print("The given string is not a palindrome.")
#include <stdio.h>
#include <string.h>
// Function to check for palindrome
int is_palindrome(char str[]) {
int len = strlen(str);
for (int i = 0; i < len / 2; i++) {
if (str[i] != str[len - i - 1]) {
return 0; // Not a palindrome
}
}
return 1; // It's a palindrome
}
int main() {
char str[100];
printf("Enter a string: ");
scanf("%s", str);
if (is_palindrome(str)) {
printf("The given string is a palindrome.\n");
} else {
printf("The given string is not a palindrome.\n");
}
return 0;
}
#include <iostream>
#include <algorithm>
using namespace std;
bool isPalindrome(string str) {
string rev = str;
reverse(rev.begin(), rev.end());
return str == rev;
}
int main() {
string str;
cout << "Enter a string: ";
cin >> str;
if (isPalindrome(str))
cout << "Palindrome";
else
cout << "Not a Palindrome";
return 0;
}
import java.util.Scanner;
public class PalindromeCheck {
public static boolean isPalindrome(String str) {
String rev = new StringBuilder(str).reverse().toString();
return str.equals(rev);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = scanner.next();
if (isPalindrome(str))
System.out.println("Palindrome");
else
System.out.println("Not a Palindrome");
}
}
strlen()
: Implement custom logic to find string length.Checking for a palindrome is a fundamental concept in programming. The approach varies slightly between languages, but the logic remains the same—reverse and compare. By practicing different variations of palindrome programs, you’ll strengthen your problem-solving skills and string manipulation expertise.