One of the most popular interview question for both freshers as well as experience is this, Pass a string as a parameter. Check whether the given String is Palindrome or not if it is Palindrome then return true otherwise return false. Before that let’s understand what is Palindrome?
What is Palindrome?
A word, phrase, or sequence that reads the same backward as forwards, e.g. madam or nurses run.
Test Case – 1 | |
Input: | madam |
Output: | true |
Test Case – 2 | |
Input: | Bushan |
Output: | false |
public static void main(String[] args) {
System.out.println(isPalindrome(“gadag”));
System.out.println(isPalindrome(“bushan”));
}
public static boolean isPalindrome(String str) {
char[] c = str.toCharArray();
int last = c.length – 1;
for(int first = 0; first < last; first++, last–) {
if(c[first] != c[last]) {
return false;
}
}
return true;
}
}
[/java]
#include <string.h>
int main(){
char string1[20];
int i, length;
int flag = 0;
printf(“Enter a string:”);
scanf(“%s”, string1);
length = strlen(string1);
for(i=0;i < length ;i++){
if(string1[i] != string1[length-i-1]){
flag = 1;
break;
}
}
if (flag) {
printf(“%s is not a palindrome”, string1);
}
else {
printf(“%s is a palindrome”, string1);
}
return 0;
}
[/c]