In: Computer Science
answer in c++ ,
Write the definition of the function NthOccurrence() whose header
is int NthOccurrence(Array& data,const T& value,int n)
template It returns the index of the nth occurrence of value in
data. If n is not positive, value appears less than n times in data
or data is empty, it returns -1.
int NthOccurrence(Array &data, const T &value, int n)
{
int i = 0;
while (n > 0)
{
// found
if (data[i] == value)
{
// if n is 1
if (n == 1)
return i;
// decrement n
n--;
}
}
// not found n times or -ve n
return -1;
}