Data Structures using C++
Consider the definition the following function template:
template <class Type>
Type func(Type list[], int size)
{
Type x = list[0];
Type y = list[size - 1];
for (int j = 1; j < size / 2; j++)
{
if (x < list[j])
x = list[j];
if (y > list[size - 1 - j])
y = list[size - 1 - j];
}
return x + y;
}
Further suppose that you have the following declarations
int list[10] = {4,2,10,18,14,19,25,13,21,35};
string strList[] = {"One", "Three", "Six", "Five", "Two", "Four"};
What is the expected output of the following statement?
cout << func(list, 10) << endl;
What is the expected output of the following statements?
cout << func(strList, 6) << endl;
(Trying to understand as I had a similar question and got it wrong. I executed this one the same way and got 31 for (a) and TwoOne for (b), but I'm not sure it's right because I executed a similar question the same way and got it wrong.)
Answer:
cout << func(list, 10) << endl;
this statement will give you an output 31. Let me explain. In list array, we have 10 elements. As per logic written in func, we are finding max value in first 5 elements and min value in last 5 elements. 18 is the max value in first 5 elements and 13 is the min value in last 5 elements. so x value is 18 and y value 13. So that function will return value x + y = 18 + 13 = 31.
cout << func(strList, 6) << endl;
this statement will give you an output ThreeFive not TwoOne. Let me explain. In strList array, we have 6 elements. As per logic written in func, we are finding max value in first 3 elements and min value in last 3 elements. "Three" is the max value in first 3 elements and "Five" is the min value in last 3 elements. so x value is "Three" and y value "Five". So that function will return value x + y = "Three" + "Five" = ThreeFive
Get Answers For Free
Most questions answered within 1 hours.