Find Maximum of Two Numbers with Return Values

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.

Objective

  • 1. Prompt the user to enter two different integer values.
  • 2. Implement findMaximum(int, int) to compare the inputs.
  • 3. Use a return statement to output the larger integer.
  • 4. Print the result clearly in the console output.

Example C++ Exercise

max_function.cpp Functions
#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
Functions & Modular Logic
Basic Functions Return Statement Comparison Logic Modular Design

Share this C++ Exercise

Help others master basic loops and patterns in C++.

© C++ Programming Exercises. Master the art of performance coding.