Simple Program for Function Template
On this page (6sections)
To swap the numbers using the concept of the function template.
Simple Program Function Template Algorithm/Steps:
- STEP 1: Start the program.
- STEP 2: Declare the template class.
- STEP 3: Declare and define the functions to swap the values.
- STEP 4: Declare and define the functions to get the values.
- STEP 5: Read the values and call the corresponding functions.
- STEP6: Display the results.
- STEP 7: Stop the program.
Simple Program for Function Template
#include<iostream.h>
#include<conio.h>
template<class t>
void swap(t &x, t &y) {
t temp = x;
x = y;
y = temp;
}
void fun(int a, int b, float c, float d) {
cout << "\na and b before swaping :" << a << "\t" << b;
swap(a, b);
cout << "\na and b after swaping :" << a << "\t" << b;
cout << "\n\nc and d before swaping :" << c << "\t" << d;
swap(c, d);
cout << "\nc and d after swaping :" << c << "\t" << d;
}
void main() {
int a, b;
float c, d;
clrscr();
cout << "Enter A,B values(integer):";
cin >> a>>b;
cout << "Enter C,D values(float):";
cin >> c>>d;
fun(a, b, c, d);
getch();
}
Sample Output
Enter A, B values (integer): 10 20
Enter C, D values (float): 2.50 10.80
A and B before swapping: 10 20
A and B after swapping: 20 10
C and D before swapping: 2.50 10.80
C and D after swapping: 10.80 2.50
How It Works
This C++ program demonstrates Simple Program for Function Template. It first reads the required values as input, then performs the core operation step by step, and finally prints the output shown in the Sample Output above.
- Declare the variables that hold the program’s data.
- Read the input values that the program will work with.
- Print the final result to the console so you can compare it with the sample output.
Try changing the input values and re-running the program to see how the output changes — this is the fastest way to understand how the logic behaves.
Related Pages
Learn the concept first, then study the code:
- C++ Programs — Browse all C++ Programs.
Frequently Asked Questions
What does this C++ program do?
It is a C++ example program that demonstrates Simple Program for Function Template, including the complete source code and the expected sample output.
How do I compile and run this C++ program?
Save the code in a `.cpp` file, compile it with `g++ filename.cpp -o program`, then run it with `./program` (or `program.exe` on Windows).
What concepts does this example use?
This example uses reading user input and user-defined functions, illustrating a common pattern in C++ programming.