In c++ language. Implement a function called find that takes in the following as
ID: 3882782 • Letter: I
Question
In c++ language. Implement a function called find that takes in the following as parameters (in this order):
1. The object we want to find within the array
2. A dynamic array of ANY type
3. The size of the array
This function should look within the array for the element specified and return the index position of the first instance of the element. If the element does not exist, the function should return -1.
#include<iostream>
using namespace std;
// Write your find function here
// Leave main blank, or use it for testing
int main(){
return 0;
}
Explanation / Answer
//Please see the code below , Please do thumbs up if you like the solution
#include<iostream>
using namespace std;
/*
This function should look within the array for the element specified and
return the index position of the first instance of the element.
If the element does not exist, the function should return -1.
*/
template<typename T>
int find(T searchValue,T arr[],int size)
{
for(int i=0;i<size;i++)
{
if(arr[i]==searchValue)
{
//return the index position of the first instance of the element.
return i+1;
}
}
//If the element does not exist, the function should return -1.
return -1;
}
// Leave main blank, or use it for testing
int main(){
int index=-1;
//1. The object we want to find within the array
int objectFind=5;
//2. A dynamic array of ANY type, here we are creating an dynamic array of int type
int *arry;
//3. The size of the array
int size=10;
arry =new int[size];
// filling the array with value
for(int i=0;i<size;i++)
{
arry[i]=i+1;
}
index=find(objectFind,arry,size);
cout<<"index of the search element is "<<index<<endl;
//Char type example
char *arr_ch=new char[size];
char data='a';
char searchObj='d';
//putting the value in char arr starting from 'a'
for(int i=0;i<size;i++)
{
arr_ch[i]=data+i;
}
index=find(searchObj,arr_ch,size);
cout<<"index of the search element is "<<index<<endl;
return 0;
}
OUTPUT:
index of the search element is 5
index of the search element is 4
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.