This C Program uses recursive function & searches for an element in an unsorted list and display it’s position of occurrence. The user enters the element needed to be searched.
Here is the source code of the C program to search for an element in an unsorted list. The C Program is successfully compiled and run on a Linux system. The program output is also shown below.
-
/*
-
* C Program to search for an element in a list using
-
*/
-
#include <stdio.h>
-
-
int search(int [], int, int);
-
int main()
-
{
-
int size, index, key;
-
int list[20];
-
int count = 0;
-
int i;
-
-
printf("Enter the size of the list: ");
-
scanf("%d", &size);
-
index = size;
-
printf("Printing the list:\n");
-
for (i = 0; i < size; i++)
-
{
-
list[i] = rand() % size;
-
printf("%d\t", list[i]);
-
}
-
printf("\nEnter the key to search: ");
-
scanf("%d", &key);
-
while (index > 0)
-
{
-
index = search(list, index - 1, key);
-
/* In an array first position is indexed by 0 */
-
printf("Key found at position: %d\n", index + 1);
-
count++;
-
}
-
if (!count)
-
printf("Key not found.\n");
-
return 0;
-
}
-
int search(int array[], int size, int key)
-
{
-
int location;
-
if (array[size] == key)
-
{
-
return size;
-
}
-
else if (size == -1)
-
{
-
return -1;
-
}
-
else
-
{
-
return (location = search(array, size - 1, key));
-
}
-
}
$ cc search $ a.out Enter the size of the list: 10 Printing the list: 3 6 7 5 3 5 6 2 9 1 Enter the key to search: 5 Key found at position: 6 Key found at position: 4