Program 13: Simulate currency exchange using Call by Value and Reference.
Problem Statement:: A currency exchange booth allows users to convert currencies. Before confirming, the system simulates a swap for a preview (without changing original data). In other cases, it updates the actual values permanently. Implement both behaviors using Call by Value and Call by Reference.
Problem Description:
Input: Two integer values representing two currencies (x, y).
Output: The results showing both a preview swap and an actual permanent swap.
Constraints: Call by Value must leave original data unchanged; Call by Reference must modify the original variables.
Method: Implement two distinct functions: one receiving values and another receiving memory addresses (pointers).
Pgm Logic:
Start.
Input values x and y.
Call swapByValue(x, y).
Inside: Swap local copies and print the "Preview" result.
Print x and y in main (verifying they are unchanged).
Call swapByReference(&x, &y).
Inside: Swap values at the provided addresses using pointers and print "Actual" result.
Print updated x and y in main.
Stop.
Program Code:
// Purpose: To implement and compare Call by Value and Call by Reference behaviors in a simulation.
#include <stdio.h>
void swapByValue(int a, int b) {
int temp = a;
a = b;
b = temp;
printf("Preview Swap (By Value): %d %d\n", a, b);
}
void swapByReference(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
printf("Actual Swap (By Reference): %d %d\n", *a, *b);
}
int main() {
int x, y;
printf("Enter two currency values: ");
scanf("%d %d", &x, &y);
swapByValue(x, y);
printf("After Call by Value (Original): %d %d\n", x, y);
swapByReference(&x, &y);
printf("After Call by Reference (Updated): %d %d\n", x, y);
return 0;
}
Output:
Enter two currency values: 10 20
Preview Swap (By Value): 20 10
After Call by Value (Original): 10 20
Actual Swap (By Reference): 20 10
After Call by Reference (Updated): 20 10
RESULT: Thus the program has been executed and the output was verified.
Remarks: Compiled in Code::Blocks. This program clearly demonstrates the difference between working with a copy of data versus working with the original data via pointers.
Program Explanation: In "Call by Value," the function creates temporary copies of the inputs, so the swap only exists inside the function. In "Call by Reference," the function receives the actual memory addresses, allowing it to modify the original variables permanently.
For all 2026 published C Lab Program posts Index page: click here:
For all 2026 published articles list: click here:
…till the next post, bye-bye & take care