1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
#include <iostream> using namespace std; // Function to find the maximum of two numbers using pass-by-value int findMaxByValue(int num1, int num2) { return (num1 > num2) ? num1 : num2; } // Function to find the maximum of two numbers using pass-by-reference void findMaxByReference(int num1, int num2, int &maxNum) { maxNum = (num1 > num2) ? num1 : num2; } int main() { int num1, num2; int maxByValue, maxByReference; // Input two numbers cout << "Enter the first number: "; cin >> num1; cout << "Enter the second number: "; cin >> num2; // Find maximum using pass-by-value maxByValue = findMaxByValue(num1, num2); cout << "Maximum number (pass-by-value): " << maxByValue << endl; // Find maximum using pass-by-reference findMaxByReference(num1, num2, maxByReference); cout << "Maximum number (pass-by-reference): " << maxByReference << endl; return 0; } |
Explanation:
- Pass-by-Value (
findMaxByValue
):- Function Definition:
int findMaxByValue(int num1, int num2)
- This function takes two integers
num1
andnum2
as input parameters by value (i.e., copies of the original values). - It compares the two numbers and returns the larger one.
- Function Definition:
- Pass-by-Reference (
findMaxByReference
):- Function Definition:
void findMaxByReference(int num1, int num2, int &maxNum)
- This function takes two integers
num1
andnum2
, and a reference to an integermaxNum
. - It compares
num1
andnum2
, and assigns the larger value directly to themaxNum
reference. - This allows the original variable in the calling function to be updated.
- Function Definition:
- Main Function (
main
):- The program prompts the user to enter two numbers.
- It then calculates the maximum of the two numbers using both the pass-by-value and pass-by-reference methods.
- Finally, it prints the maximum number found by each method.
Example Outputs:
Example 1:
Input:
- First Number:
15
- Second Number:
22
Output:
1 2 3 4 |
Enter the first number: 15 Enter the second number: 22 Maximum number (pass-by-value): 22 Maximum number (pass-by-reference): 22 |
Example 2:
Input:
- First Number:
8
- Second Number:
3
Output:
1 2 3 4 |
Enter the first number: 8 Enter the second number: 3 Maximum number (pass-by-value): 8 Maximum number (pass-by-reference): 8 |
Example 3:
Input:
- First Number:
5
- Second Number:
5
Output:
1 2 3 4 |
Enter the first number: 5 Enter the second number: 5 Maximum number (pass-by-value): 5 Maximum number (pass-by-reference): 5 |