I want to find an element of array by using recursion.The function takes an array and the target value. The recursion function checks whether it is an element of the given array. But unfortunately I cant set this code on it.The function always retuns ‘1’ . where do I make mistake?
#include <stdio.h>
int isElement(int *a, int target) ;
int main()
{
int a[] = {3,5,6,4,2,32,15} ;
int target = 12 ,res ;
res = isElement( a, target) ;
if(res==1)
printf("its an element of the array\n");
if(res==0)
printf("its not an element of the array\n");
return 0 ;
}
int isElement(int *a, int target)
{
int son=0 ;
printf("array = %d\n",a[0] );
if(a[1] == '\0')
son = 0 ;
else if(target == a[0])
son = 1 ;
else
son = isElement(&a[1] ,target);
return son ;
}
Your termination condition is for when
a[1] == '\0'. However, you array doesn’t terminate with a 0. Therefore you are searching fortargetout of the boundaries of the array, over the rest of the stack. This is undefined behavior, so anything could happen (and you can’t complain). However, in your specific case, it so happens thattargetis placed afteraon the stack, so once you go out ofa, you see the same value you were looking for, hence always returning 1.What you should do is change the definition of
ato:Also, the condition:
will give you wrong results in such an example:
Because before checking for
a[0] == target, you mark this case as fail. Therefore you should change the condition to: