C Program to search element in array using recursion

Simple C Program to search element in array using recursion: If array is {2,8,5,1,8,9,3}; and number is 5 to search then program will print "number is at index 2 or if number is 8 then program will print "number is at index 1" , "number is at index 4". If number is 20 then program will print that number is not in array.
#include<stdio.h>
void FindElement(int arr[],int n,int num)
{
 if(n<0)
 return ;
 
 FindElement(arr,n-1,num);
 if(arr[n]==num)
 printf("Num is at index %d\n",n);
}
int main()
{
 int arr[]={2,5,2,9,4,12,2,8,2};
 int n=sizeof(arr)/sizeof(arr[0]);
 int c=0,i=0,num;
 printf("Enter number to search: ");
 scanf("%d",&num);
 for(i=0;i<n-1;i++)
 {
  if(arr[i]==num)
  {
  c=1;
  break;
 }
 }
 if(c)
 FindElement(arr,n-1,num);
 else
 printf("Number is not in the array\n");
 return 0;
}


Popular posts from this blog