Sunday 12 November 2017

C Program Count the Number of Occurrences of an Element in the Linked List using Recursion


Code:

#include   stdio.h

void occur(int [], int, int, int, int *);

int main()
{
    int size, key, count = 0;
    int list[20];
    int i;

    printf("Enter the size of the list: ");
    scanf("%d", &size);
    printf("Printing the list:\n");
    for (i = 0; i < size; i++)
    {
        list[i] = rand() % size;
        printf("%d    ", list[i]);
    }
    printf("\nEnter the key to find it's occurence: ");
    scanf("%d", &key);
    occur(list, size, 0, key, &count);
    printf("%d occurs for %d times.\n", key, count);
    return 0;
}

void occur(int list[], int size, int index, int key, int *count)
{
    if (size == index)
    {
        return;
    }
    if (list[index] == key)
    {
        *count += 1;
    }
    occur(list, size, index + 1, key, count);
}

Output:

Enter the size of the list: 7
Printing the list:
1    4    2    5    1    3    3
Enter the key to find it's occurence: 3
3 occurs for 2 times.


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...