Home » C program to search an element in an array using recursion

C program to search an element in an array using recursion

Below is the code to search an element in an array using recursion

#include <stdio.h>
int srch(int array[],int x,int j){
    if(array[x]==j){
        return 1;
    }
    else if(x>=0){
            srch(array,x-1,j);
    }
    else{
        return 0;
    }
    
}
int main(){
    int i,x,j;
    printf("Enter number of elements do you want to enter: ");
    scanf("%d",&x);
    int array[x];
    printf("Enter elements:");
    for(i=0;i<x;i++){
        scanf("%d",&array[i]);
    }
    printf("Elemnets in the array are: ");
    for(i=0;i<x;i++){
        printf("%d\n",array[i]);
    }
    printf("Enter element to be searched:");
    scanf("%d",&j);
    int y=srch(array,x,j);
    if(y==1){
        printf("Element found");
    }
    else{
        printf("Element not found");
    }
   
}

Contents

Output 1:

Enter number of elements do you want to enter: 6
Enter elements:3
4
5
6
7
8
Elemnets in the array are: 3
4
5
6
7
8
Enter element to be searched:1
Element not found

Output 2:

Enter number of elements do you want to enter: 4
Enter elements:5
6
7
4
Elemnets in the array are: 5
6
7
4
Enter element to be searched:5
Element found