Template Programming Exercise 3 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 3

Write a class template that inputs the index of the array and displays the value in the specified index.

#include<iostream>
using namespace std;

template <class Type>
class Test 
{
	private:
		Type arr[5];
		public:
			void input()
			{
				for(int i = 0; i < 5; i++)
				cin>>arr[i];
			}
			void show()
			{
		int i;
		cout<<"\nEnter an index: ";
		cin>>i;
		cout<<"The value at required index: "<<arr[i];
			}
};
   main()
   {
   	Test <int> x;
   	Test <char>y;
   	cout<<"\nEnter five integers: "<<endl;
   	x.input();
   	x.show();
   	cout<<"\nEnter five characters: "<<endl;
   	y.input();
   	y.show();
   }

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

Leave a Reply