Write a program using function template to find the sum of first and last element of an array.
Sep 2, 2019Source code:
//program to find the sum of first and last element of
//an array using function template
#include <iostream>
using namespace std;
//function template defination
template <class Type>
Type sum_first_last(Type arr[], int SIZE){
Type sum;
sum = arr[0] + arr[SIZE - 1];
return sum;
}
int main()
{
int i_arr[] = {1,2,3,4,5}, i_size = sizeof(i_arr)/sizeof(int);
float f_arr[] = {1.1,2.2,3.3};
int f_size = sizeof(f_arr)/sizeof(float);
cout<<"Result of integer array = "<<sum_first_last(i_arr, i_size)<<endl;
cout<<"Result of float array = "<<sum_first_last(f_arr, f_size)<<endl;
return 0;
}
Sample run:
Result of integer array = 6 Result of float array = 4.4