-1

i am writing a function in which to check that the given array is a palendrome or not using recursion.

int pal(char p[], int i, int j) {
  if (i > j) return 1;
  if (p[i] != p[j]) {
    return 0;
  }
  pal(p, i++, j--);
}

void palTest() {
  char p1[] = "hello";
  char p2[] = "elle";
  int x;
  x = pal(p1, 0, 4);
  if (x == 0)
    printf("p1 is not a palendrom\n");
  else
    printf("p1 is a palendrom\n");
  x = pal(p2, 0, 3);
  if (x == 0)
    printf("p2 is not a palendrom\n");
  else
    printf("p2 is a palendrom\n");
}

void main() { 
    palTest(); 
}

I expected the program to write p2 is a palindrome but it did not print anything.

Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
Abo Ali
  • 81
  • 5

1 Answers1

4

The function pal

int pal(char p[],int i, int j)
{
if (i > j)
return 1;
    if (p[i] != p[j])
    {
        return 0;
    }
pal(p, i++, j--);
}

has undefined behaviour because it returns nothing in case when not i > j and not p[i] !+ p[j].

You have to write

int pal(char p[],int i, int j)
{
if (i > j)
return 1;
    if (p[i] != p[j])
    {
        return 0;
    }
    return pal(p, ++i, --j);
}

Also pay attention to that you have to use the pre-increment and pre-decrement operators.

    return pal(p, ++i, --j);

Otherwise you are passing to a next call of the function pal the same values of i and j.

Also the first parameter of the function should have the qualifier const.

The function can be defined much simpler with using only two parameters.

Here is your program with the updated function definition and its calls.

#include <stdio.h>
#include <string.h>

int pal( const char *s, size_t n )
{
    return n < 2 ? 1 : s[0] == s[n-1] && pal( s + 1, n - 2 ); 
}

void palTest( void )
{
    char p1[] = "hello";
    char p2[] = "elle";
    int x;

    x = pal( p1, strlen( p1 ));
    if (x == 0)
        printf("p1 is not a palendrom\n");
    else
        printf("p1 is a palendrom\n");

    x = pal( p2, strlen( p2 ) );
    if (x == 0)
        printf("p2 is not a palendrom\n");
    else
        printf("p2 is a palendrom\n");
}


int main(void) 
{
    palTest();

    return 0;
}

Instead of the conditional operator in the return statement of the function you could use a logical expression like

int pal( const char *s, size_t n )
{
    return ( n < 2 ) || ( s[0] == s[n-1] && pal( s + 1, n - 2 ) ); 
}

Bear in mind that according to the C Standard the function main without parameters shall be declared like

int main( void ).
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335