Write a function template called total. The function will keep a running total of values entered by the user, then return the total. The function will accept one int argument that is the number of values the function is to read. Test the template in a simple program that would prompt the user to enter the number of values to read and then read these values from stdin and output the total. The program will repeat this procedure first for integers, then for doubles.

Respuesta :

Answer:

The template is given in C++

Explanation:

#include <iostream>

using namespace std;

//Template function that returns total of all values entered by user

template <class T>

T total (int n)

{

   int i;

   //Initializing variables

   T sum = 0, value;

   //Prompting user

   cout << "\n Enter " << n << " values: \t ";

   //Iterate till user enters n values

   for(i=1; i<=n; i++)

   {

       //Reading a value

       cin >> value;

       //Accumulating sum

       sum = sum + value;

   }

   //Return sum

   return sum;

}

//Main function

int main()

{

   int n;

   //Reading n value

   cout << "\n Enter number of values to process: ";

   cin >> n;

   //Calling function for integers and printing result

   cout << "\n\n Total : " << total<int>(n);

   cout << "\n\n";

   //Function call for doubles and printing results

   cout << "\n\n Total : " << total<double>(n);

   cout << "\n\n";

   return 0;

}