Write a program in C++ using the template function to add elements of the array.

Program Code:
#include <iostream> 
using namespace std; 
template<class T> 

// template function
T sum(T a[], int length)
{
T ret = a[0];
for (int i = 1; i < length; i ++)
ret += a[i];
return ret;
}

int main(void) 
{
int int_data[5];
float float_data[5];
int i = 0;
cout << "5 integer"<< endl;
for (; i <5; i++)
cin >> int_data[i];
// template function call using integer array
cout << "Sum="  << sum(int_data, 5) << endl;
cout << "5 floats"<< endl;
for (i = 0; i < 5; i ++)
cin >> float_data[i];
// template function call using float array
cout <<"sum of float=" << sum(float_data, 5) << endl;
cin.get();
return 0;
}
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: