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 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
#include <iostream> using namespace std; // Function to calculate profit or loss using pass-by-value void calculateProfitOrLossByValue(int costPrice, int sellingPrice) { int result; if (sellingPrice > costPrice) { result = sellingPrice - costPrice; cout << "Profit (By Value): " << result << endl; } else if (costPrice > sellingPrice) { result = costPrice - sellingPrice; cout << "Loss (By Value): " << result << endl; } else { cout << "No Profit, No Loss (By Value)" << endl; } } // Function to calculate profit or loss using pass-by-reference void calculateProfitOrLossByReference(int &costPrice, int &sellingPrice, int &result, string &status) { if (sellingPrice > costPrice) { result = sellingPrice - costPrice; status = "Profit"; } else if (costPrice > sellingPrice) { result = costPrice - sellingPrice; status = "Loss"; } else { result = 0; status = "No Profit, No Loss"; } } int main() { int costPrice = 1000, sellingPrice = 1200; int result; string status; // Calculate using pass-by-value cout << "Pass-by-Value Calculation:" << endl; calculateProfitOrLossByValue(costPrice, sellingPrice); // Calculate using pass-by-reference cout << "\nPass-by-Reference Calculation:" << endl; calculateProfitOrLossByReference(costPrice, sellingPrice, result, status); cout << status << " (By Reference): " << result << endl; return 0; } |
Explanation
- calculateProfitOrLossByValue Function:
- This function takes two integers,
costPrice
andsellingPrice
, as parameters by value. - It calculates the profit or loss by comparing the
sellingPrice
with thecostPrice
. - Since this function uses pass-by-value, any changes made to the parameters inside the function do not affect the original variables.
- This function takes two integers,
- calculateProfitOrLossByReference Function:
- This function takes two integers (
costPrice
andsellingPrice
) and two additional references (result
andstatus
) as parameters. - It calculates the profit or loss and updates the
result
andstatus
variables directly. - Since this function uses pass-by-reference, the original variables are modified with the result of the calculation.
- This function takes two integers (
Output
1 2 3 4 5 |
Pass-by-Value Calculation: Profit (By Value): 200 Pass-by-Reference Calculation: Profit (By Reference): 200 |
Key Points
- Pass-by-Value: The original
costPrice
andsellingPrice
values remain unchanged after the function call. - Pass-by-Reference: The
result
andstatus
variables are updated with the calculated profit or loss after the function call.