Monday 13 November 2017

C Program using Recursion to Search an Element in Array


Code:

#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));
    }
}


Output:

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


More C Programs:
















100+ Best Home Decoration Ideas For Christmas Day 2019 To Make Home Beautiful

Best gifts for Christmas Day | Greeting cards for Christmas Day | Gift your children a new gift on Christmas day This Christmas d...