Thread: palindrome HELP !!!

  1. #1
    Registered User
    Join Date
    Oct 2001
    Posts
    13

    Question palindrome HELP !!!

    I would appreciate it if you’ s could help me out on the following code. I have a piece of code, which finds if a palindrome exists on the word entered (palindrome is a string that is spelt the same way forwards as backwards) which works perfectly. However I have a file to be opened in command line arguments and assuming that the file in this case to be opened is “palindrome.txt” and containing a palindrome of text within this file (example = i saw radar was i), I have to print to the screen whether this file contains a palindrome or not after it is opened through command line argument (i.e argv, argc). Combining the 2 pieces of code below or thereabouts I think it will allow me to do this, but I am unsure on how to write it. The output might look as follows “palindrome.txt contains 5 words (i saw radar was i) and contains a palindrome”. It would be of great help if the code below were rewritten for me in order to achieve this. Thanks a lot !

    //code to find out whether a word is a palindrome
    int main(void)
    {
    char string[50];
    int tag, count, back, flag=1;

    puts("Enter a word : ");
    for(count = 0; (string[count] = getchar()) != '\n'; ++count);
    tag = count - 1;

    for((count = 0, back = tag); count <= tag/2; (++count, --back))
    {
    if(string[count] != string[back])
    {
    flag = 0;
    break;
    }
    }

    for(count = 0; count <= tag; ++count)
    putchar(string[count]);

    if(flag == 1)
    puts(" is a palindrome\n");
    else
    puts(" is not a palindrome\n");



    getch();
    }



    //code to find out whether file contains palindrome text when opened - unfinsihed
    int main (int argc, char *argv[])
    {
    FILE *FilePtr; /* Pointers to the File */
    char LineRead[100];
    int Count=0, i;


    if (argc==2)
    {/* Open the file palindrome.txt for Reading */
    if( (FilePtr=fopen("palindrome.txt", "r")) == NULL)
    printf("ERROR OPENING FILE\n");
    else
    { /* File Opened so...*/
    /* While LineRead != End Of File */
    while( (fgets(LineRead, 100, FilePtr) ) != NULL) /* Read Line from palindrome.txt */
    {
    /* Ensure i is zero */
    i=0;
    /* Add one to Count for next line - if its not '\n' */
    if(strcmp(LineRead, "\n") != 0)
    Count++;
    /* Count the number of spaces in the Line Read */
    while(LineRead[i] != '\0')
    {
    if(LineRead[i++]==' ')
    Count++;
    }
    }
    }

    /* Display the number of words in the file */
    printf("%d words in %s ", Count, argv[1]);
    /* Close the Files */
    fclose(FilePtr);
    }

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    > It would be of great help if the code below were rewritten for
    > me in order to achieve this. Thanks a lot !

    What would be a great help to me, is if people did their homework on their own and stopped posting about it.

    What also would be a good help is if people actually used the
    search for this board.

    Quzah
    Hope is the first step on the road to disappointment.

  3. #3
    Registered User Nutshell's Avatar
    Join Date
    Jan 2002
    Posts
    1,020
    hi TED22_8,

    I just done your exercise recently, and i seeked help from ppl in this forum. Here's a tip. Create a function called palindrome or somethin like that and include as its parameters the string array, starting position and the ending position. One way to test the string is to reverse the string and compare it with the original one. The way i used was to compare the first character with the last character (ignoring '\0') and keep going recursively until there's one character left or the last two characters are equal or not.

  4. #4
    Registered User
    Join Date
    Sep 2001
    Posts
    4,912
    The message above just jogged my memory of something. Can you return an entire array from functions or do you have to use pointers? What about structs?

  5. #5
    Registered User Nutshell's Avatar
    Join Date
    Jan 2002
    Posts
    1,020
    no, i think your can't return arrays. But your function's suppose to test the string and return 1 if palindrome and 0 otherwise. My version is a recursive one.

  6. #6
    Registered User
    Join Date
    Oct 2001
    Posts
    13

    improvents

    thanks for replies, getting places now with it

  7. #7
    Banned Troll_King's Avatar
    Join Date
    Oct 2001
    Posts
    1,784
    If you use the free store you can return a reference to an array from the called function.

    Code:
    #include<stdlib.h>
    #include<stdio.h>
    #include<string.h>
    
    char * ReverseWord(char[],int);
    int main()
    {
    	char buffer[30];
    	char word[30];
    	char * word_rev;
    
    	printf("Enter word: ");
    	fgets(buffer,30,stdin);
    	buffer[strlen(buffer)-1] = '\0';
    
    	if( (sscanf(buffer,"%s",word) != 1) ) exit(1);
    
    
    	word_rev = ReverseWord(word,strlen(word)+1);
    
    	if( strcmp(word,word_rev) == 0 )
    		printf("%s is a pallindrome.",word);
          free(word_rev);
    	return 0;
    }
    
    char * ReverseWord(char a[],int size)
    {
    	char *b = (char*) malloc (sizeof(char) * size);
    	if(b == NULL) exit(2);
    
    	char *ptr = b;
    	int i;
    
    	for(i = strlen(a) - 1; i >= 0; i--)
    	{
    		*(ptr++) =  a[i];
    	}
    	*ptr = '\0';
    
    	return b;
    }
    Last edited by Troll_King; 01-20-2002 at 01:51 AM.

  8. #8
    Registered User
    Join Date
    Dec 2001
    Posts
    421
    why dont you just use something like this:

    Code:
    int Palindrome(char* word)
    {
       int i = 0;
       char* start = word;
       char* end = word + strlen(word) - 1;
    
       for(i = 0; i < strlen(word); i++, start++, end--)
       {
            if(toupper(*start) != toupper(*end))
            {
                return(0);
            }
       }
    
       return(1);
    }
    please note that this code hasn't been compiled or tested... you should get the idea though.

    U.
    Quidquid latine dictum sit, altum sonatur.
    Whatever is said in Latin sounds profound.

  9. #9
    Registered User
    Join Date
    Nov 2001
    Posts
    65
    int palindrome(char string[], int size)
    {
    if (size == 0 || size == 1)
    return 1;
    else if (string[0] != string[size - 1])
    return 0;
    else
    return palindrome(&string[1], size - 2);
    }

    the size is the length of the string. Calculate it with strlen and send it to the function.
    The experimenter who does not know what he is looking for will not understand what he finds.
    - Claude Bernard

  10. #10
    Registered User
    Join Date
    Dec 2001
    Posts
    421

    Talking

    There's no need to use recursion here... a simple loop does the job... as demonstrated by the code i posted...

    you could even refine that further.... but it's the best code so far.

    U.
    Quidquid latine dictum sit, altum sonatur.
    Whatever is said in Latin sounds profound.

  11. #11
    Unregistered
    Guest
    no, i think your can't return arrays. But your function's suppose to test the string and return 1 if palindrome and 0 otherwise. My version is a recursive one.
    Troll_King wrote his version because someone had asked this question. Infact you can return a reference to an array that is allocated on the free store.

    As far as the other versions go, they look okay. I like the recursive one myself. When I have time I'll have to read up on recursion some more.

  12. #12
    Unregistered
    Guest
    how about...

    Code:
    #include <string.h>
    
    bool TestForPalindrome(char *chTxt)
    {
    char *chTmp=new char[strlen(chTxt)+1];
    //store the incoming string
    strcpy(chTmp,chTxt);
    //reverse incoming string
    strrev(chTxt);
    //compare the original and reversed strings
    if (!strcmp(chTxt,chTmp))
        {
        //strings are equal so palidrome is found
        delete[] chTmp;
        return true;
        }
    else
        {
        //no match so not palindrome
        delete[] chTmp;
        return false;
        }
    }
    How's that?

  13. #13
    erstwhile
    Join Date
    Jan 2002
    Posts
    2,227
    ooops... forgot to login so couldn't edit my suggestion using strrev.

    I just wanted to rename 'TestForPalindrome' fn as IsPalindrome as it makes more sense (to me anyway). And to correct typo of
    'palidrome' to palindrome.

    ...

    ok I really just wanted to see my contributions reach the dizzy heights of 2

    I don't do much C so if 'new' is bad then replace:

    char *chTmp=new char[strlen(chTxt)+1];

    with:

    char *chTmp=(char*)malloc(sizeof(char)*strlen(chTxt));

    and replace all instances of:

    delete[] chTxt;

    with:

    free(chTxt);

    Sorry for any confusion caused.

    *********************************************

    One last correction. Replace:

    strrev(chTxt);

    with:

    strrev(chTmp);

    To prevent real nasty error.

    Last edited by Ken Fitlike; 01-21-2002 at 07:46 PM.

  14. #14
    Registered User
    Join Date
    Dec 2001
    Posts
    421
    i'll tell you why... because the use of strrev, recursion, malloc and/or any other function is a huge amount of overhead for something so simple...

    if a string is a palindrome, you only have to check the first half of the string against the second half of the string.

    also, everyone else's suggestions are case sensative.... are you trying to tell me that "Radar" is not a palindrome??? coz those methods you have suggested will not produce the required result.

    Radar and radar are both palindromes.

    Code:
    int IsPalindrome(char* text)
    {
       char* start = text;
       char* finish = text + strlen(text) - 1;
       for(int i = 0; i < (finish - start) / 2; i++, start++, finish--)
       {
          if(toupper(*start) != toupper(*end))
          {
             return(0);
          }
       }
       return(1);
    }
    U.
    Quidquid latine dictum sit, altum sonatur.
    Whatever is said in Latin sounds profound.

  15. #15
    Banned Troll_King's Avatar
    Join Date
    Oct 2001
    Posts
    1,784
    The only reason why somone would say that recursion causes overhead when testing a pallindrome is because they have one testicle.

    If you want to convert to uppercase use toupper.
    Last edited by Troll_King; 01-22-2002 at 12:15 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Error in Recursive String Palindrome Code
    By clegs in forum C Programming
    Replies: 13
    Last Post: 12-21-2008, 12:36 PM
  2. Is it a Palindrome?
    By xp5 in forum C Programming
    Replies: 3
    Last Post: 09-06-2007, 05:26 AM
  3. bool palindrome definition
    By justinc911 in forum C++ Programming
    Replies: 3
    Last Post: 11-26-2003, 05:50 PM
  4. Palindrome
    By Ginny Morgan in forum C Programming
    Replies: 7
    Last Post: 05-08-2003, 04:04 PM
  5. Palindrome Coding trouble
    By TheLoneWolf32 in forum C++ Programming
    Replies: 3
    Last Post: 02-22-2003, 07:05 PM