Dec 16, 2011

Whether it is palindrome or not, recursively 2nd part


Well the idea came to me in the other post was more simple than I imagined, and now the recursive function itself looks much better, it's much more than a disguised cycle.
Extensively commented code, so here it is:
 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 # Include <string.h>
 # Include <iostream>
 using namespace std;
 int len, n = 0;

 chk4palindrosity string (string Thestra)
 {
     if (Thestra [0] == Thestra [Thestra. length () - 1]) / / compare first character with last
     {
         n + +;
         if (n == len / 2) / / if the number of times the comparison was true is ...
             return "If palindrome!" / / equal to half of the caracters is palindrome
         Thestra. erase (0, 1) / / delete first character
         Thestra. erase (thestr. length () - 1, 1) / / delete last
         chk4palindrosity return (Thestra) / / call the function with the string cut
     }
     else / / if one of the comparisons is true, is not a palindrome
         return "is not palindrome";
 }

 int main ()
 {
     inputf char [50] = {0}, input [50], * part;
     court <<"Enter a palindrome:"; cin. getline (input, '\ n');

     part = strtok (input, "") / /
     strcat (inputf, part) / /
     while ((part = strtok (NULL, ""))! = NULL) / /
         strcat (inputf, part) / / remove spaces from array

     Thestra string (inputf) / / convert string array to facilitate operations
     len = Thestra. length () / / get the string LENGTH
     if (len == 1)
         court <<"If palindrome!"
     else
         court <<chk4palindrosity (Thestra) / / call function and print what return
     cin. get ();
 } 
What makes the recursive function is to compare the first character to the last, if they are equal trim and knock: if not, it is palindrome. Any doubt already know that the comments are open.

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Premium Wordpress Themes