Pass-by-Value
In this approach, the function receives a copy of the hours
and minutes
, so any changes made within the function do not affect the original variables.
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 |
#include <iostream> using namespace std; // Function to determine AM or PM (pass-by-value) void determineAMPM(int hours, int minutes) { if (hours >= 0 && hours < 12) { cout << (hours == 0 ? 12 : hours) << ":" << (minutes < 10 ? "0" : "") << minutes << " AM" << endl; } else if (hours >= 12 && hours < 24) { cout << (hours == 12 ? 12 : hours - 12) << ":" << (minutes < 10 ? "0" : "") << minutes << " PM" << endl; } else { cout << "Invalid hour value!" << endl; } } int main() { int hours, minutes; cout << "Enter hours (0-23): "; cin >> hours; cout << "Enter minutes (0-59): "; cin >> minutes; determineAMPM(hours, minutes); return 0; } |
Pass-by-Reference
In this approach, the function receives references to hours
and minutes
, allowing any changes made within the function to affect the original variables.
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 |
#include <iostream> using namespace std; // Function to determine AM or PM (pass-by-reference) void determineAMPM(int& hours, int& minutes) { if (hours >= 0 && hours < 12) { cout << (hours == 0 ? 12 : hours) << ":" << (minutes < 10 ? "0" : "") << minutes << " AM" << endl; } else if (hours >= 12 && hours < 24) { cout << (hours == 12 ? 12 : hours - 12) << ":" << (minutes < 10 ? "0" : "") << minutes << " PM" << endl; } else { cout << "Invalid hour value!" << endl; } } int main() { int hours, minutes; cout << "Enter hours (0-23): "; cin >> hours; cout << "Enter minutes (0-59): "; cin >> minutes; determineAMPM(hours, minutes); return 0; } |
Explanation
- Pass-by-Value: The
determineAMPM
function receives copies ofhours
andminutes
. It performs the AM/PM conversion logic based on these copies. The original variables inmain
are not modified. - Pass-by-Reference: The
determineAMPM
function receives references tohours
andminutes
. This allows the function to work directly with the variables frommain
. However, in this case, there are no modifications tohours
andminutes
, so the effect of pass-by-reference is similar to pass-by-value.
Sample Output
Assuming you enter 14
for hours and 30
for minutes:
For Pass-by-Value:
1 2 3 |
Enter hours (0-23): 14 Enter minutes (0-59): 30 2:30 PM |
For Pass-by-Reference:
1 2 3 |
Enter hours (0-23): 14 Enter minutes (0-59): 30 2:30 PM |