Skip to main content

Posts

Showing posts with the label function template program

Write a program using function template that ask user to enter the 10 elements in the array of type int and float and display the five largest value in ascending order.

 Here's a program using function templates to find the five largest values in an array of integers or floats in ascending order: #include <iostream> #include <algorithm> using namespace std; template <typename T> void findLargestValues(T arr[], int size, int n) {     // sort the array in descending order     sort(arr, arr + size, greater<T>());     // print the largest n values in ascending order     cout << "The " << n << " largest values are: ";     for (int i = 0; i < n; i++) {         cout << arr[size - i - 1] << " ";     }     cout << endl; } int main() {     int intArr[10];     float floatArr[10];     // read integers from user input     cout << "Enter 10 integers: ";     for (int i = 0; i < 10; i++) {         cin >> intArr[i];     ...

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++){     ...