This blog is about providing theory as well as simple executable codes of different programming languages such as java, C, C++, and web programming, etc. This blog will be helpful to the IT students to learn about programming.

Tuesday, February 21, 2023

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++){
        cin >> arr2[i];
    }
    cout << "Sum of first and last elements of int array: " << sum_first_last(arr1, n) << endl;
    cout << "Sum of first and last elements of float array: " << sum_first_last(arr2, n) << endl;
    return 0;
}

In the above program, the sum_first_last() function is a template function that takes an array arr of type T and the size of the array N as arguments. The function returns the sum of the first and last elements of the array.

In the main() function, we create two arrays of different types (int and float) and call the sum_first_last() function for each array. The compiler automatically generates two separate versions of the sum_first_last() function for the two different types.

No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget