Write a template function to find the maximum number from a template array of size N.

Sep 2, 2019

Source code:

//program to find the maximum of array template

#include <iostream>
using namespace std;
const int N = 6;

template <class Type>
Type find_max(Type arr[], int SIZE){
    Type max_temp = arr[0];
    for(int i = 1; i < SIZE; i++){
        if(arr[i] > max_temp){
            max_temp = arr[i];
        }
    }
    return max_temp;
}


int main(){
    //trying with floating array
    float f_arr[N];
    //read the array elements
    cout<<"Enter array elements:";
    for(int i = 0; i < N; i++){
        cin>>f_arr[i];
    }
    cout<<"Maximum Element is: "<<find_max(f_arr, N);
    return 0;
}

 

Sample run:

Enter array elements:1.2
7.8
9.9
4.4
3.3
2.3
Maximum Element is: 9.9