In-Class Exercise

Function Template


This exercise defines a template for generating functions that calculate the sum of the elements of an array.


Your Task

Template

Define a template for generating functions named sum() that receive the address of an array and the number of elements in the array and that return the sum of the elements in the array. 

 // Function Template
 // sum.h


      sum(         , int n) {




      return    ;
 }

Client Module

The compiler generate from your template the functions that the following client program requires.  The results of execution are shown on the right:

 // Function Template
 // h18.cpp

 #include <iostream>
 #include <iomanip>
 #include "sum.h"

 int main() {
     int a[] = {1, 2, 3, 4, 5, 6};
     float b[] = {1.5, 2.5f, 3.5f, 4.5f, 5.5f, 6.5f};
     double c[] = {1.5, 2.5, 3.5, 4.5, 5.5, 6.5};

     std::cout << std::fixed << std::setprecision(2);
     std::cout << "Sum of a[] = " << sum(a, 6)
               << std::endl; 
     std::cout << "Sum of b[] = " << sum(b, 6)
               << std::endl;
     std::cout << "Sum of c[] = " << sum(c, 6)
               << std::endl;
 }













 Sum of a[] = 21

 Sum of b[] = 24.00 

 Sum of c[] = 24.00








  Designed by Chris Szalwinski   Copying From This Site   
Logo
Creative Commons License