#include<iostream.h>
#include<conio.h>
template <class myType>
myType amax (myType *arr, int size)
{
int i;
myType max=-9999;
myType max = arr[ 0 ];
for( i = 1; i < size; i++)
{
if(arr[i] > max)
{
max = arr[i];
}
}
cout<<"\nMax is :"<<max;
return max;
}
int main()
{
int arri[5]={1,2,3,4,5};
float arrf[5]={-11.12,-2,3,4,5.12};
clrscr();
amax(arri,5);
amax(arrf,5);
getch();
return 0;
}
It is because, normally we won't enter negative numbers as input. But, if you enter input ( all numbers ) below -9999, then you will get wrong answer for that. Please check with input
int arri[5]={ -11111, -22222, -33333, -44444, -55555}.
I hope, now, you understood why I initialized with the first element of the array. Also, to make it complete answer, we need to check the size to be greater than zero which reflects there were some valid numbers in the array.
Last, but not least, as the value of the max got printed in the function itself, I don't find any need to return the largest value to the function called. Thus, void may be expected as return type or the max value be get printed in the function called.
Still need any assistance / clarification ? Remember! CRAMSTER is always there to SOLVE PROBLEMS.