C Program using Recursion to Search an Element in Array
Posted by Superadmin on July 05 2019 22:15:39

C Program using Recursion to Search an Element in Array

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.

  1. /*
  2.  * C Program to search for an element in a list using
  3.  */
  4. #include <stdio.h>
  5.  
  6. int search(int [], int, int);
  7. int main()
  8. {
  9.     int size, index, key;
  10.     int list[20];
  11.     int count = 0;
  12.     int i;
  13.  
  14.     printf("Enter the size of the list: ");
  15.     scanf("%d", &size);
  16.     index = size;
  17.     printf("Printing the list:\n");
  18.     for (i = 0; i < size; i++)
  19.     {
  20.         list[i] = rand() % size;
  21.         printf("%d\t", list[i]);
  22.     }
  23.     printf("\nEnter the key to search: ");
  24.     scanf("%d", &key);
  25.     while (index > 0)
  26.     {
  27.         index = search(list, index - 1, key);
  28.         /* In an array first position is indexed by 0 */
  29.         printf("Key found at position: %d\n", index + 1);
  30.         count++;
  31.     }
  32.     if (!count)
  33.         printf("Key not found.\n");
  34.     return 0;
  35. }
  36. int search(int array[], int size, int key)
  37. {
  38.     int location;
  39.     if (array[size] == key)
  40.     {
  41.         return size;
  42.     }
  43.     else if (size == -1)
  44.     {
  45.         return -1;
  46.     }
  47.     else
  48.     {
  49.         return (location = search(array, size - 1, key));
  50.     }
  51. }

 

$ 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