A word is called palindrome if reads the same backward as forward, for
example: madam, level, and racecar. Write a program that reads a string as an input
and prints out if that string is a palindrome or not. Your program should implement a
function that takes only a pointer of char for that string and check whether it is a
palindrome string or not. You are not allowed to use the string function length( ),
however, you can define your own length function instead. [Hint: you need to define
another pointer and define the size of the string].
Answers
Answer:
import java.util.Scanner;
class palindrome
{
static String reverse(String s)
{
char[] letters = new char[s.length()];
int ind = 0;
for(int i = s.length() - 1; i >= 0; i--)
{
letters[ind] = s.charAt(i);
ind++;
}
String reversed = "";
for(int i = 0; i < s.length(); i++)
{
reversed = reversed + letters[i];
}
return reversed;
}
static boolean isPalindrome(String str)
{
if(reverse(str).equals(str))
{
return true;
}
else
{
return false;
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string:");
String x = sc.nextLine();
if(isPalindrome(x))
{
System.out.println(x + " is a palindrome");
}
else
{
System.out.println(x + " is not a palindrome");
}
}
}
Explanation: