Simple Function Template Array Program Example : Search Number in C++
On this page (6sections)
Generic Programming
Templates are a feature of the C++ programming language that allows functions and classes to operate with generic types
Function Template Definition
A function template behaves same as normal function except that the template works with different data types.
Function Template Syntax
template <class identifier> function_declaration;
template <typename identifier> function_declaration;
templete_identifier fn_name(templete_identifier .. args) {
return ...
}
Example Program
// Header Files
#include <iostream>
#include<conio.h>
#include<stdlib.h>
#define MAX_SIZE 5
using namespace std;
// Template Declaration
template<class T>
// Generic Template Function for Search
T getSearch(T x[], T element) {
int i;
cout << "\nYour Data :";
for (i = 0; i < MAX_SIZE; i++) {
cout << "\t" << x[i];
}
/* for : Check elements one by one - Linear */
for (i = 0; i < MAX_SIZE; i++) {
/* If for Check element found or not */
if (x[i] == element) {
cout << "\nFunction Template : Element : " << element << " : Found : Position : " << i + 1 << ".\n";
break;
}
}
if (i == MAX_SIZE)
cout << "\nSearch Element : " << element << " : Not Found \n";
}
int main() {
int arr_search[MAX_SIZE], i, element;
float f_arr_search[MAX_SIZE], f_element;
cout << "Simple Function Template Array Program Example : Search Number\n";
cout << "\nEnter " << MAX_SIZE << " Elements for Searching Int : " << endl;
for (i = 0; i < MAX_SIZE; i++)
cin >> arr_search[i];
cout << "\nEnter Element to Search (Int) : ";
cin>>element;
// Passing int Array to Template Function
getSearch(arr_search, element);
cout << "\nEnter " << MAX_SIZE << " Elements for Searching Float : " << endl;
for (i = 0; i < MAX_SIZE; i++)
cin >> f_arr_search[i];
cout << "\nEnter Element to Search (Float) : ";
cin>>f_element;
// Passing int Array to Template Function
getSearch(f_arr_search, f_element);
getch();
return 0;
}
Sample Output
Simple Function Template Array Program Example : Search Number
Enter 5 Elements for Searching Int :
56
34
100
23
90
Enter Element to Search (Int) : 23
Your Data : 56 34 100 23 90
Function Template Search : Element : 23 : Found : Position : 4.
Enter 5 Elements for Searching Float :
45.23
89.01
90.67
100.89
23.90
Enter Element to Search (Float) : 23.90
Your Data : 45.23 89.01 90.67 100.89 23.9
Function Template Search : Element : 23.9 : Found : Position : 5.
Related Pages
Continue learning with these related tutorials and programs:
- OOP Programs — Browse all OOP Programs.
- Templates in C++ — Concept — function and class templates.
- Simple Class Template Program Example Get Maximum Number — More in templates in c.
- Simple Class Template Array Program Example : Search Number — More in templates in c.