Search Position of Nth Times Occurred Element in an Array

Previously we have written a C program to search an element in an array, now this times we will write a C program to search the position of Nth times occurred element in an array.

Program description:- Write a program to search elements occurrence in an array. If an element found only after that it should ask the user to enter the occurrence of an element.

Sample input / outputs of this program, Array = {5, 6, 2, 5, 9, 6, 5}

Enter element to search: 8
8 not found.

Enter element to search: 5
Enter times of occurrence of element: 3
5 found 3 times at 7 position.

Enter element to search: 9
Enter times of occurrence of element: 2
9 not found 2 times.

Enter element to search: 6
Enter times of occurrence of element: 1
6 found 1 time at 2 positions.

C Program to Search Position of Nth Times Occurred Element

#include<stdio.h>
int main()
{
   int a[100], n, element;
   int i, found=0, count=0, pos=0;

   printf("Enter array size [1-100]: ");
   scanf("%d", &n);

   // take array elements
   printf("Enter array elements: ");
   for(i=0; i<n; i++) scanf("%d", &a[i]);

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

   for(i=0; i<n; i++)
   {
     if(a[i]==element)
     {
       count++;
       if(count==1)
       {
         printf("Enter times of occurance of element: ");
         scanf("%d",&pos);
       }
       if(count==pos)
       {
         found++;
         printf("%d found %d times at %d position.",element,pos,i+1);
         break;
       }
     }
   }

   if(count==0) printf("%d not found.", element);
   else if(found==0) printf("%d not found %d time.",element,pos);

   return 0;
}

Output for the different test-cases:-

PrepBytes
Use Code KNOWPROGRAM10 to get FLAT 10% OFF on all Courses

Enter array size [1-100]: 5
Enter array elements: 1 1 2 3 2
Enter element to search: 2
Enter times of occurrence of element: 2
2 found 2 times at 5 position.

Enter array size [1-100]: 8
Enter array elements: 80 50 20 80 50 20 20 10
Enter element to search: 5
5 not found.

Enter array size [1-100]: 3
Enter array elements: 1 2 3
Enter element to search: 3
Enter times of occurrence of element: 2
3 not found 2 time.

Previously we found an element using linear search. but we can’t find the occurrence of the element which occurred more than once. So in this program, we will search the position of Nth times occurred element in an array.

If the element not found then it will display "element not found", and If an element not found nth times then it will be displayed "element not found the nth time".

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *