Write a generic C++ function that takes an array of genericelements and a scalar of the same type as the array elements. Thetype of the array elements and the scalar is the generic parameter.The function must search the given array for the given scalar andreturn the subscript of the scalar in the array. If the scalar isnot in the array, the function must return -1. Test the function for int and float types.
Requirements:
1. Write a main function to make it acomplete program.
2. Initialize the array with random numbers.

Respuesta :

Answer:

Explanation:

Here is the code

#include<iostream>

using namespace std;

template <class myType>

int generic(myType *a, myType b)

{

int i;

for(i=0;a[i]!=-1;i++)

{

       if( b == a[i])

       return i;

}

return -1;

}

int main()

{

int a[]={1,2,3,4,5,6,7,8,-1};

float b[]={1.1,2.1,3.1,4.1 ,5.1,6.1,7.1,-1};

if(generic(a,5)>0)

       {

       cout<<" 5 is foundin int at index "<<generic(a,5)<<endl;

       }

       else

       {

       cout<<" 5 notfound "<<endl;

       }

if(generic(b,(float)5.1)>0)

       {

       cout<<" 5.1 isfound in float at index "<<generic(a,5)<<endl;

       }

       else

       {

       cout<<" 5.1 notfound "<<endl;

       }

system("pause");

}

/*

sample output

5 is found in int at index 4

5.1 is found in float at index 4

*/

ACCESS MORE
EDU ACCESS