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
Show 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