#include <iostream>
using namespace std;
int max_of_four(int a, int b, int c, int d) {
int max_value = a;
if (b > max_value) {
max_value = b;
}
if (c > max_value) {
max_value = c;
}
if (d > max_value) {
max_value = d;
}
return max_value;
}
int main() {
int a, b, c, d;
cin >> a >> b >> c >> d;
int max_val = max_of_four(a, b, c, d);
cout << max_val << endl;
return 0;
}
Let's break down the code and explain each part:
#include
using namespace std;: This statement allows us to use the standard library functions without explicitly specifying the namespace (e.g., cout, cin).
int max_of_four(int a, int b, int c, int d) { ... }: This is a function named max_of_four that takes four integer arguments (a, b, c, d) and returns an integer value. Inside the function, we declare a variable max_value and initialize it with the value of a. We then compare b, c, and d with max_value using if statements and update max_value if a greater value is found. Finally, we return max_value as the result of the function.
int main() { ... }: This is the main function of the program. It is the entry point for execution.
int a, b, c, d;: We declare four variables a, b, c, and d to store the input values.
cin >> a >> b >> c >> d;: This statement reads four input values from the user and assigns them to the variables a, b, c, and d using the >> operator.
int max_val = max_of_four(a, b, c, d);: We call the max_of_four function and pass the values of a, b, c, and d as arguments. The returned value is assigned to the variable max_val.
cout << max_val << endl;: This statement outputs the value of max_val using cout and appends a newline character (endl) to the output.
return 0;: This line indicates that the program execution is successful and returns the value 0 to the operating system.
When you run this program, it will prompt the user to enter four values (a, b, c, and d). It will then call the max_of_four function with these values and output the maximum value among them.
To use this code in HackerRank's "Functions" problem, you can copy and paste it into the editor and submit it. The program will prompt the user for input, and the output will be displayed in the output window or terminal, depending on the HackerRank environment.
Make sure to read the problem statement and input/output requirements carefully and adjust the code accordingly if needed.