Skip to main content

Posts

Showing posts with the label template

What is a template and why do we use Template in OOP? WAP to swap to variables using Function Template.

 A template is a C++ feature that allows creating a single code template for a group of related functions or classes that can work with different data types. It enables generic programming and helps to write more flexible and reusable code. We use templates in OOP to create generic classes and functions that can work with multiple data types without having to write the same code for each data type separately. It reduces the code's redundancy and simplifies maintenance. Here's a program to swap two variables using Function Template: #include <iostream> using namespace std; template <typename T> void swapValues(T &a, T &b) {     T temp = a;     a = b;     b = temp; } int main() {     int x = 10, y = 20;     float p = 3.14, q = 6.28;     char c1 = 'A', c2 = 'B';     swapValues(x, y);     swapValues(p, q);     swapValues(c1, c2);     cout << "After Swapping: " ...

Define template. write a program using function temple to find the sum of first and last element of an array of size, N of type int and float.

 A template is a feature in C++ that allows a programmer to create a generic class or function that can work with different types of data. Templates make the code more reusable and allow the programmer to write a single implementation that can be used with multiple data types. Here is an example program that uses a function template to find the sum of the first and last elements of an array of size N: #include <iostream> using namespace std; template <typename T> T sum_first_last(T arr[], int N) {     return arr[0] + arr[N-1]; } int main() {  int n;     cout << "Enter the number of elements: ";     cin >> n;     int arr1[n];     cout << "Enter the integers: ";     for (int i = 0; i < n; i++){         cin >> arr1[i];     }  int arr2[n];     cout << "Enter the floats: ";     for (int i = 0; i < n; i++){     ...