Sabri Mevis
Sabri Mevis

Reputation: 2431

Finding an element of an array using recursion in c

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 ;

}

Upvotes: 0

Views: 3957

Answers (4)

sashang
sashang

Reputation: 12194

'a' isn't a null terminated string so this test here:

if(a[1] == '\0')
  son = 0 ;

is wrong.

Your function returns 1 because it keeps reading past the end of the array invoking undefined behaviour. On another computer, and I compiled and ran it on mine, the function returns 0. On my machine the program doesn't find 12. However on your machine it behaves differently. This is the consequence of undefined behaviour.

Upvotes: 0

aasa
aasa

Reputation: 207

Wrong line:

  if(a[1] == '\0')
      son = 0 ;

int a[] doesn't ended by symbol '\0', so your code will visit illegal memory.

for int a[], for function should be defined as follows:

int isElement(int *a, int arraylength, int target) ;

and in every recurion loop, the arraylength -1.

The ended compare should be:

if(arraylength == 1 && a[0] != target)
son = 0;

Upvotes: 0

Shahbaz
Shahbaz

Reputation: 47523

Your termination condition is for when a[1] == '\0'. However, you array doesn't terminate with a 0. Therefore you are searching for target out 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 that target is placed after a on the stack, so once you go out of a, you see the same value you were looking for, hence always returning 1.

What you should do is change the definition of a to:

int a[] = {3,5,6,4,2,32,15, 0} ;
                           ^^^

Also, the condition:

if(a[1] == '\0')
      son = 0 ;

will give you wrong results in such an example:

int a[] = {12, 0};
int target = 12;

Because before checking for a[0] == target, you mark this case as fail. Therefore you should change the condition to:

     vvv
if (a[0] == 0)
    son = 0;

Upvotes: 0

yhyrcanus
yhyrcanus

Reputation: 3813

a is not a string, so there is no null terminator ('\0'). You need to pass an array length, or else this function will continue in memory forever (until it finds it).

Upvotes: 3

Related Questions