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.

Monday, February 27, 2023

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];
    }
    // find the 5 largest integers
    findLargestValues(intArr, 10, 5);
    // read floats from user input
    cout << "Enter 10 floats: ";
    for (int i = 0; i < 10; i++) {
        cin >> floatArr[i];
    }
    // find the 5 largest floats
    findLargestValues(floatArr, 10, 5);
    return 0;
}

In this program, we define a function template findLargestValues that takes an array of type T, its size, and the number of largest values to find. The function first sorts the array in descending order using the sort function and greater comparator. It then prints the largest n values in ascending order using a loop.

In the main function, we declare two arrays intArr and floatArr of size 10 to store user input. We read integers and floats from user input using a loop and then call the findLargestValues function template twice, once for the intArr array and once for the floatArr array, to find the 5 largest values in each array.

No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget