Write a program using function template to find the sum of first and last element of an array.
Sep 23, 2018Program Source Code:
#include<iostream> using namespace std; #define N 4 template< class T> T get_sum(T arr[], int SIZE){ return arr[0] + arr[SIZE - 1]; } int main(){ int int_array[N]; float float_array[N]; cout<<"Enter integer array elements:"<<endl; for (int i = 0; i < N; i++) { cin>>int_array[i]; } cout<<"Enter floating array elements:"<<endl; for (int i = 0; i < N; i++) { cin>>float_array[i]; } cout<<"Sum of first and last element of integer array :"<<get_sum(int_array,N)<<endl; cout<<"Sum of first and last element of floating array :"<<get_sum(float_array,N)<<endl; return 0; }
Sample Run:
Enter integer array elements: 2 3 4 5 Enter floating array elements: 34.44 3.4 34.34 4.44 Sum of first and last element of integer array :7 Sum of first and last element of floating array :38.88