In: Computer Science
Task 2/2: Java program
Based upon the following code:
public class Main { public static void main( String[] args ) { String alphabet = "ABCDEFGHIJKLMNMLKJIHGFEDCBA"; for( <TODO> ; <TODO> ; <TODO> ) { <TODO>; } // Closing for loop } // Closing main() } // Closing class main() |
Write an appropriate loop definition and in-loop behavior to determine if the alphabet string is a palindrome or not. A palindrome is defined as a string (or more generally, a token) which has the same value when read front-to-back as back-to-front.
palindrome is a type of string it gives same result if we read from right or left .Therefore corresponding positions from left and right will be equal
public class Main {
public static void main( String[] args ) {
String alphabet =
"ABCDEFGHIJKLMNMLKJIHGFEDCBA";
int len=alphabet.length(); //string length
int flag=0;
for( int i= 0; i<len/2 ; i++ ) { // we iterate through half of the string palindrome compare characters from left and right
if(alphabet.charAt(i)!=alphabet.charAt(len-i-1)){
flag=1;
// set flag to 1 if not a palindrome and break the loop
break;
}
} // Closing for loop
if(flag==0){ // if flag unchanged then its a
palindrome
System.out.println("given string is a palindrome");
}
else{
System.out.println("given string is not a palindrome");
}
} // Closing main()
} // Closing class main()