Find the Maximum of Two Numbers Using a Function
This exercise focuses on modular programming in C++. You will create a program that delegates the comparison logic to a custom function. Mastering functions is crucial for writing reusable, organized, and scalable code in real-world software development.
Logic Components
1. Function Prototype
Defining int findMaximum(int a, int b) allows the program to accept two integer parameters and return a single integer result.
2. Comparison Logic
Using an if-else block inside the function isolates the decision-making process from the main execution flow.
3. Return Value
The return statement sends the larger value back to the main() caller to be displayed or processed.
Key Learning Objectives:
- Parameter Passing: Understanding how data moves from
main()to sub-functions. - Function Scope: Recognizing that variables inside the function are independent of the caller.
- Code Reusability: Learning to write logic once and call it multiple times.
Objective
- 1. Prompt the user to enter two different integer values.
- 2. Implement
findMaximum(int, int)to compare the inputs. - 3. Use a
returnstatement to output the larger integer. - 4. Print the result clearly in the console output.
Example C++ Exercise
#include <iostream>
using namespace std;
// Function to find the maximum between two numbers
int findMaximum(int a, int b) {
if (a > b) {
return a;
} else {
return b;
}
}
int main() {
int num1, num2;
cout << "Enter the first number: ";
cin >> num1;
cout << "Enter the second number: ";
cin >> num2;
// Call the function and store the returned value
int maxResult = findMaximum(num1, num2);
cout << "The maximum of the two numbers is: " << maxResult << endl;
return 0;
}
Console Output:
Enter the first number: 42
Enter the second number: 17
The maximum of the two numbers is: 42