max function in c++
#include <iostream>
using namespace std;
template <typename T>
T max(T a, T b) {
return (a > b) ? a : b;
}
int main() {
int intMax = max(10, 5);
double doubleMax = max(7.5, 12.3);
cout << "Maximum of 10 and 5 is: " << intMax << endl;
cout << "Maximum of 7.5 and 12.3 is: " << doubleMax << endl;
return 0;
}
Explanation:
#include <iostream>
: Includes the Input/Output Stream Library to enable input/output streams.using namespace std;
: Enables the usage of standard library functions and objects without specifying the namespace each time.template <typename T> T max(T a, T b) { return (a > b) ? a : b; }
: Defines a template functionmax
that takes two parameters of typeT
and returns the greater value among them using the conditional operator? :
.int main() { ... }
: The main function where program execution begins.int intMax = max(10, 5);
: Calls themax
function with integers10
and5
as arguments and stores the result in the variableintMax
.double doubleMax = max(7.5, 12.3);
: Calls themax
function with doubles7.5
and12.3
as arguments and stores the result in the variabledoubleMax
.cout << "Maximum of 10 and 5 is: " << intMax << endl;
: Outputs the maximum of10
and5
.cout << "Maximum of 7.5 and 12.3 is: " << doubleMax << endl;
: Outputs the maximum of7.5
and12.3
.return 0;
: Indicates successful completion of the main function and the program terminates.