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.

Friday, March 17, 2023

Write a function template for finding the minimum value contained in an array in C++ program.

 here's an example of a function template for finding the minimum value contained in an array in C++:

#include <iostream>
using namespace std;

template<typename T>
T findMin(T arr[], int size) {
    T minVal = arr[0];
    for(int i = 1; i < size; i++) {
        if(arr[i] < minVal) {
            minVal = arr[i];
        }
    }
    return minVal;
}

int main() {
    int intArr[] = {4, 8, 2, 10, 5};
    double doubleArr[] = {2.5, 6.7, 1.2, 4.5};
    
    cout << "Minimum value in intArr: " << findMin(intArr, 5) << endl;
    cout << "Minimum value in doubleArr: " << findMin(doubleArr, 4) << endl;
    return 0;
}

In this example, we define a function template findMin that takes an array of any type (T) and its size as parameters. The function iterates through the array and compares each element to the current minimum value. If an element is smaller than the current minimum value, it becomes the new minimum value. Finally, the function returns the minimum value.

In the main function, we test the findMin function on an integer array and a double array, printing the minimum value of each array. The output should be:

Minimum value in intArr: 2
Minimum value in doubleArr: 1.2

No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget