Sunday, February 25, 2018

C program : A function to find the kth occurrence of an integer n in a sequence of non-negative integers

You are given the input in two lines:

The first line contains a non-negative integer, say n, and a positive
integer k, in that order. You have to find the kth occurrence of n in
the sequence below. (When

The second line consists of a sequence of non-negative integers,
terminated with a -1.  The -1 is not part of the sequence.


#include<stdio.h>


int find(int n, int k)
{
     int num, count= -1, ocurr=0;
  while(num != -1)
{
    scanf("%d", &num);
    count++;
    if(num==n)
    {
        ocurr++;

    }
    if(ocurr==k)
    {
        return count;
    }

  }
if(ocurr<k){return -1;}

}

int main(){
 int n,k,i;
  scanf("%d %d" , &n,&k);

  i=find(n,k);
   printf("%d",i);

}
Thanks
Happy Computing !

No comments:

Post a Comment

How can I run a C++ program directly from Windows?

How-can-I-run-a-C-program-directly-from-Windows