Template Programming Exercise 1 in C++

Template Programming are the base of generic programming. The main advantage of template is that we don’t have to create different functions for different data types. Datatype is passed as a parameter in template. “template” keyword is used to define a template.

If you want to practice with Functions Programming Exercises kindly read the following article.

Syntax:

template <class type> return_type fun_name(parameters)
{
   // function defination
} 

If you want to practice with Arrays kindly read the following article.

Question Number 1

Write a function template that finds the minimum value in the array and returns it.

#include<iostream>
using namespace std;

template <class Type>
Type Max(Type a[], int l)
{
	Type max = a[0];
	for(int i = 0; i < l; i++)
	  if(a[i] > max)
	     max = a[i];
	return max;     
}
  main()
  {
  	int n[5], m, i;
  	float avg[5], am;
  	cout<<"Enter five integers: ";
  	for(i = 0; i < 5; i++)
  	   cin>>n[i];
  	m = Max(n, 5);
  	cout<<"Maximum value: "<<m<<endl;
	cout<<"Enter five floating point numbers: ";
	  for(i = 0; i < 5; i++)
	  cin>>avg[i];
	  am = Max(avg, 5);
	  
          cout<<"Maximum value: "<<am<<endl;	    
  }

If you want to practice with OOP Programming Exercises kindly read the following article.

Leave a Reply