Home »
C/C++ Data Structure Programs
C program to search an item in an array using recursion
In this tutorial, we will learn how to search an item in an array using recursion in C language?
By Nidhi Last updated : August 10, 2023
Problem statement
Create an array of integers, then search an array element using recursion and print the index of the item.
C program to search an item in an array using recursion
The source code to search an item in an array using recursion is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.
// C program to search an item in array
// using the recursion
#include <stdio.h>
int searchItem(int arr[], int len, int item)
{
if (arr[len] == item)
return len;
else if (len == -1)
return -1;
else
return searchItem(arr, len - 1, item);
}
int main()
{
int arr[] = { 23, 10, 46, 21, 75 };
int index = 0;
int item = 0;
printf("Enter item to search: ");
scanf("%d", &item);
index = searchItem(arr, 5, item);
if (index == -1)
printf("Item not found in array\n");
else
printf("Item found at index %d\n", index);
return 0;
}
Output
RUN 1:
Enter item to search: 46
Item found at index 2
RUN 2:
Enter item to search: 75
Item found at index 4
RUN 3:
Enter item to search: 99
Item not found in array
Explanation
Here, we created two functions searchItem() and main(). The searchItem() is a recursive function, which is used to search an item in the array and return the index of the item to the calling function.
In the main() function, we created an array of integers arr with 5 elements. Then we searched the item in the array and printed the index of the item in the array.