Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Q1. (Function/operator overloading) Write a C++ program that overloads a functio

ID: 3560579 • Letter: Q

Question

Q1. (Function/operator overloading)

Write a C++ program that overloads a function named LinearSearch that searches an array of data of either integer data type, float, or double for a specific data. Test it in main by creating and assigning values to an array of integers, float, and double and searching each of them for some specific data.

Please circle the part that is doing function/operator overloading and explain the advantages of using function/operator overloading in your code.

Q2. (Template)

Now change the code in Q1 to by using template. It should do the same task and produce same output.

Please circle the part that is defining and using template.

Compare the different advantages of using function overloading and template in your code.

Q3. (STL)

Now change the code in Q2 by using the

Explanation / Answer

You can have multiple definitions for the same function name in the same scope. The definition of the function must differ from each other by the types and/or the number of arguments in the argument list. You can not overload function declarations that differ only by return type. This makes code easy to understand.

Below code define same function LinearSearch which searches element of different types and return the index of the element in the array, if found else return -1.

#include <iostream>

using namespace std;

//Function overloading: Same function works for different data types
int LinearSearch(int arr[], int size, int searchElement){
for(int iter = 0 ; iter< size ; iter++){
if(arr[iter] == searchElement){
return iter;
}
}
return -1;
}
int LinearSearch(float arr[], int size, float searchElement){
for(int iter = 0 ; iter< size ; iter++){
if(arr[iter] == searchElement){
return iter;
}
}
return -1;
}
int LinearSearch(double arr[], int size, double searchElement){
for(int iter = 0 ; iter< size ; iter++){
if(arr[iter] == searchElement){
return iter;
}
}
return -1;
}

int main()
{
int a1[5] = {2,4,10,1,6};
float a2[5] = {2.0,4.1,10.11,1.3,6.7};
double a3[5] = {2.011,4.134,10.3511,1.367,6.7123};

//calling LinearSearch to search integer
cout<<LinearSearch(a1,5,4)<<endl;

//calling LinearSearch to search float
cout<<LinearSearch(a2,5,2.0)<<endl;

//calling LinearSearch to search double
cout<<LinearSearch(a3,5,1.367)<<endl;

return 0;
}

Output:

1

0

3

C++ templete can also used here. You dont have copy the definition three times in that case.