Practice Program 5.7:
! A palindrome is a sequence of characters that reads the same backward and forward.
! Punctuation marks and spaces are ignored. No distinction is made betwen
! lowercase and uppercase letters. An example palindrome is the following string:
! "Name no one man".
! Ask the user to enter a string and determine if this string is a palindrome.
! test for Hannah, George, "Able was I ere I saw Elba", "Name no one man"
! Pseudocode:
! 1. remove all characters that are not letters
! 2. make all letters capital
! 3. make a reverse version
! 4. compare the original with the reverse
! 5. if not equal print "The string is not a palindrome"
! 6. if equal print: "The string is a palindrome"
! PP5.7.1 clean and capitalize the string:
!LET ccaps$ = ucase$("Name no one man")
!PRINT "the capitalized string is ..."; ccaps$
!LET word$ = ""
!LET index = len(ccaps$)
!LET j=0
!DO until j= index
! LET j=j+1
! LET B$=ccaps$[j:j]
! PRINT B$
! IF ord(B$) <90 and ord(B$)>64 then
! LET word$ =word$&B$
! ELSE
! LET B$=""
! PRINT word$
! END IF
!LOOP
!PRINT word$
!END
! Practice program PP5.7.2 to make a reverse version of cleanword$
! LET word$ = "SAMENOONEMAN"
! LET revword$=""
! FOR n = len(word$) to 1 step -1
! LET revword$= revword$&word$[n:n]
! NEXT n
! PRINT "the original word is...", word$
! PRINT "the reversed word is...", revword$
! END
! The main program
INPUT prompt "Please enter a phrase...":word$
!LET word$= "Name no one man"
! 2. make all letters capital
LET capword$= UCASE$(word$)
PRINT "capword$ is ...",capword$
! 1. remove all characters that are not letters
LET cleanword$=""
LET j=0 ! initialize control variable for do loop
LET index = len(capword$) ! the range of the do loop control variable
DO until j= index
LET j=j+1
LET B$=capword$[j:j] !test each letter in capword$
IF ord(B$) <90 and ord(B$)>64 then !test for capital letters
LET cleanword$ =cleanword$&B$ ! build up cleanword$
ELSE
LET B$="" ! throw away noncaps in capword$
PRINT cleanword$ !see how it stands as the loop works
END IF
LOOP
PRINT "cleanword$ is...", cleanword$
LET revword$="" ! initialize
FOR n = len(cleanword$) to 1 step -1
LET revword$= revword$&cleanword$[n:n]
NEXT n
PRINT "the original phrase is...", word$
PRINT "the reversed phrase is...", revword$
IF revword$=cleanword$ then
PRINT "the phrase is a palindrome"
ELSE
PRINT "the phrase is not a palindrome"
END IF
END
Sample output:
Please enter a phrase...Able was I ere I saw Elba
capword$ is ... ABLE WAS I ERE I SAW ELBA
ABLE
ABLEWAS
ABLEWASI
ABLEWASIERE
ABLEWASIEREI
ABLEWASIEREISAW
cleanword$ is... ABLEWASIEREISAWELBA
the original phrase is... Able was I ere I saw Elba
the reversed phrase is... ABLEWASIEREISAWELBA
the phrase is a palindrome