Create an Array Summing Function Template in CPP


//A program to define a function template
//for summing an array of integers and an
//array of floating point numbers//

#include <iostream.h>
#include<conio.h>

template<class T> T sum (T *array, int n)
{
   T temp = 0;
   for(int i=0; i<=n-1; i++)
   temp = temp+array[i];
   return(temp);
}

int sum (int *a, int n);
float sum(float *b,int n);
void main()

{
   clrscr();
   int n = 3,sum1;
   float sum2;
   static int a[3] = {1,2,3};
   static float b[3] = {1.1,2.2,3.3};
   sum1 = sum(a,n);
   cout << " sum of the integers = " << sum1 << endl;
   sum2 =sum(b,n);
   cout << " sum of the  floating point numbers = " << sum2;
   cout<< endl;
   getch();
}

No comments:

Post a Comment

Custom Search