Find the Maximum of Two Numbers Using a Function in C++

This C++ exercise is designed to help you practice working with functions. You will write a simple program that asks the user to input two numbers and then uses a function to determine which of the two is greater. Functions in C++ allow for reusable, modular code and help in organizing logic in a clear and concise way.

By completing this exercise, you will reinforce your understanding of how to define and call functions, pass arguments, and return values. The logic will also include conditional comparisons to find the larger of two values.

Group

Functions in C++

Objective

1. Prompt the user to enter two integer values.
2. Define a function that takes two integers as parameters and returns the greater one.
3. Call the function with the user's input and display the result.
4. Use conditional statements inside the function to determine which number is greater.

Write a function that calculates the maximum between two numbers.

Example C++ Exercise

 Copy C++ Code
#include <iostream> // Include the iostream library for input and output

using namespace std; // Use the standard namespace

// Function to find the maximum between two numbers
int findMaximum(int a, int b) {
    // Use a conditional statement to compare the two numbers
    if (a > b) {
        return a; // If 'a' is greater, return 'a'
    } else {
        return b; // Otherwise, return 'b'
    }
}

// Main function - starting point of the program
int main() {
    int num1, num2; // Variables to store user input

    // Prompt the user to enter the first number
    cout << "Enter the first number: ";
    cin >> num1; // Read the first number

    // Prompt the user to enter the second number
    cout << "Enter the second number: ";
    cin >> num2; // Read the second number

    // Call the findMaximum function and store the result
    int max = findMaximum(num1, num2);

    // Display the maximum of the two numbers
    cout << "The maximum of the two numbers is: " << max << endl;

    return 0; // End of the program
}

 Output

Enter the first number: 42
Enter the second number: 17
The maximum of the two numbers is: 42

Enter the first number: 5
Enter the second number: 11
The maximum of the two numbers is: 11

Share this C++ Exercise


More C++ Programming Exercises of Functions in C++

Explore our set of C++ Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C++. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C++.