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;
}
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;
}
Post A Comment:
0 comments: