# C program to search an item in the linked list using recursion

In this tutorial, we will learn how to search an item in the linked list using recursion using the C program? By Nidhi Last updated : August 02, 2023

## Problem statement

Create a linked list, search the specified items into a created linked list using the recursion, and print the index.

## C program to search an item in the linked list using recursion

The source code to search an item in the linked list 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 the linked list
// using recursion

#include <stdio.h>
#include <stdlib.h>

//Self referential structure to create node.
typedef struct tmp {
int item;
struct tmp* next;
} Node;

typedef struct
{
Node* tail;

} List;

//Initialize List
void initList(List* lp)
{
lp->tail = NULL;
}

//Create node and return reference of it.
Node* createNode(int item)
{
Node* nNode;

nNode = (Node*)malloc(sizeof(Node));

nNode->item = item;
nNode->next = NULL;

return nNode;
}

//Add new item at the end of list.
{
Node* node;
node = createNode(item);

//if list is empty.
lp->tail = node;
}
else {
lp->tail->next = node;
lp->tail = lp->tail->next;
}
}

//Add new item at begning of the list.
{
Node* node;
node = createNode(item);

//if list is empty.
lp->tail = node;
}
else {
}
}

//To print list from start to end of the list.
void printList(List* lp)
{
Node* node;

printf("\nEmpty List");
return;
}

printf("List:\n");
while (node != NULL) {
printf("| %05d |", node->item);
node = node->next;

if (node != NULL)
printf("--->");
}
printf("\n\n");
}

void SearchItem(Node* node, int item)
{
static int index = 0;

if (node->item == item) {
printf("Item found at index: %d\n", index);
return;
}
if (node->next == NULL) {
return;
}

index++;
SearchItem(node->next, item);
}

//Main function to execute program.
int main()
{
List* lp;

int item = 0;

lp = (List*)malloc(sizeof(List));

initList(lp);

printList(lp);

printf("Enter item to search: ");
scanf("%d", &item);

return 0;
}
```

## Output

```RUN 1:
List:
| 00300 |--->| 00200 |--->| 00100 |--->| 00150 |

Enter item to search: 100
Item found at index: 2

RUN 2:
List:
| 00300 |--->| 00200 |--->| 00100 |--->| 00150 |

Enter item to search: 400
```

## Explanation

Here, we created a self-referential structure to implement a linked list, a function to add a node at the start and end of the list, a recursive function SearchItem() to search a specified item into the created list.

In the main() function, we created the linked list and read an item from the user to search into the linked list then we searched the item using the SearchItem() function and printed the location of the item in the linked list.