Example & Tutorial understanding programming in easy ways.

Write a function to determine whether or not a string is a palindrome?.

A palindrome is a string that can be read from right to left, and yet still remains the same as the string read left to right. For example, ‘racecar’ and ‘level’ are both palindromes because if you read the strings from right to left they are equivalent to the strings read left to right.

So, how shoud we approach writing a function that, given a string as input, determines whether or not that string is a palindrome? What is the defining feature of a palindrome? That, when read from right to left it is the same as the string read left to right.

What if we just create a temporary string where we store the string read from right to left, and then compare that to the original string. If they are the same, then it’s a palindrome, if different then the string is NOT a palindrome. Sounds simple enough, here’s what the pseudocode would look like:

example: madam

import java.util.*;

class Palindrometest{

public static void main(String args[]){

String orig, rev="";

Scanner in = new Scanner(System.in);

System.out.println("Enter a string to check if it is a palindrome");

orig = in.nextLine();

int length = orig.length();

for ( int i = length - 1 ; i >= 0 ; i-- )

rev = rev + orig.charAt(i);

if (orig.equals(rev))

System.out.println("Entered string is a palindrome.");

else

System.out.println("Entered string is not a palindrome.");       }}               


  

Read More →