209k views
4 votes
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.

User Ryan Davis
by
8.1k points

1 Answer

5 votes

Answer:

The template is given in C++

Step-by-step 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 << "\\ 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 << "\\ Enter number of values to process: ";

cin >> n;

//Calling function for integers and printing result

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

cout << "\\\\";

//Function call for doubles and printing results

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

cout << "\\\\";

return 0;

}

User Jennykwan
by
8.7k points