Question: I created a recursive and iterative palindrome program that determines whether the string entered is a palindrome or not. A semi-formal recursive definition of a

I created a recursive and iterative palindrome program that determines whether the string entered is a palindrome or not.

A semi-formal recursive definition of a palindrome

a) what is the recursive step

b) create appropriate comments for both the recursive and iterative programs.

recursive

import java.io.*; public class RecursivePalindrome { static boolean CheckPalindrome(String s, int leftSide, int rightSide) { if (rightSide <= leftSide) return true; else if (s.charAt(leftSide) != s.charAt(rightSide)) return false;

else return CheckPalindrome(s,leftSide+1,rightSide-1);

} public static void main(String[] args) throws IOException {

String str; int n;

InputStreamReader inStream = new InputStreamReader( System.in ); BufferedReader stdin = new BufferedReader( inStream ); System.out.print("Please enter any string: "); str = stdin.readLine();

int lastPosition = str.length()-1;

boolean result = CheckPalindrome(str , 0, lastPosition); if (result)

System.out.println("The string \""+str+"\" is a palindrome ");

else

System.out.println("The string \""+str+"\" is not a palindrome ");

}

}

iterative

import java.util.Scanner; public class Iterative { public static void main(String args[]) {

Scanner reader=new Scanner(System.in); System.out.println("please enter a string"); String input=reader.nextLine();

System.out.printf("Is %s a palindrome? : %b %n", input, isPalindrome(input));

System.out.println("please enter another string"); input=reader.nextLine();

System.out.printf("Is %s a palindrome? : %b %n", input, isPalindrome(input));

reader.close();

} public static boolean isPalindrome(String input) { if(input==null || input.isEmpty()) { return true; }

char[] array=input.toCharArray(); StringBuilder sb=new StringBuilder(input.length()); for(int i=input.length() -1; i>=0; i--) { sb.append(array[i]);

} String reverseOfString=sb.toString(); return input.equals(reverseOfString);

} }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!