Hi guys. so I have been trying to solve this problem and I wrote a program but it doesn't work for some reason I would apreciate a help from you guys.

The problem:
A palindrome is a word, phrase, or any other sequence of letters that can be spelled the same way in either direction. For example, “level” and “noon” are palindromes. Write a recursive logical-function that returns 1 if the word is a palindrome and 0 otherwise. You may do it by matching the first letter with the last, the second with the next-to-last, and so on. Matching letters should be non-case- sensitive that is upper case letters match lower case letters. Notice that a single letter is not considered a palindrome.
Write a driver (main) function to prompt the user to enter a sentence. Use your recursive logical- function to count the number of palindromes in that sentence. You need to use String Tokenization (strtok) function to split the sentence into words.

The code :

#include <stdio.h>
    #include <string.h>
    #include <ctype.h>
    #define SIZE 81

    int fun(char str[ ],int size);
    int rec_fun(char str[ ],int size);

    int main(void){
        int sum;
        char str[SIZE];
        printf("Enter a sentence: \n");
        sum=fun(str, SIZE);
        gets(str);
        rec_fun(str,SIZE);
        printf("the sentance have %d pelidorum", sum);

        getch();
        return(0);
    }

    int fun(char str[  ],int size){
        int flag, i, len, sum=0;

        len=strlen(str);
        for(i=0; i<len/2; i++){
          if(tolower(str[len+i])==tolower(str[len-1])){
            flag=1;
            continue;}
          else
          flag=0;
          break;}
        if(flag)
        sum+=1;
        return sum;
    }

    int rec_fun(char str[ ],int size){
        char *token; int sum;
        token= strtok(str," ");

        if(NULL)
         return 0;
        else
         return  fun(strtok(token,NULL), size);
         }

OK, here is Python solution for model. I give this, as I do not want to give ready solution. Instead of slicing out ends of string for recursion you must find C version to do it or use extra parameters.

def pali(s):
    # if longer than one and ends match, True if shorter than 4 else recursion with ends removed, otherwise false
    # odd case is handled as 3 long, not one long as one long defined not as palindrome
    return len(s) > 1 and s[0].lower() == s[-1].lower() and (len(s) in (2, 3) or pali(s[1:-1]))

# split to words and feed to pali, sum the result and print
print sum(pali(s) for s in 'Hanah is driving a civic at noon'.split())

"""Output:
3
"""

Edited 4 Years Ago by pyTony

This article has been dead for over six months. Start a new discussion instead.