C Program to Swap Two Numbers using Call by Reference
This program swaps two numbers in C using the concept of call by reference. It demonstrates how pointers can be used to modify the actual values of variables passed to a function.
Concept Overview
In call by reference, instead of passing copies of values, the memory addresses (pointers) of variables are passed to the function. This allows the function to directly modify the original variables.
Program
C
#include <stdio.h>
// Function to swap two numbers using call by reference
void swap(int *x, int *y) {
int temp = *x;
*x = *y;
*y = temp;
}
int main() {
int a = 10, b = 20;
printf("Before swap, value of a : %d\n", a);
printf("Before swap, value of b : %d\n", b);
swap(&a, &b);
printf("After swap, value of a : %d\n", a);
printf("After swap, value of b : %d\n", b);
return 0;
}
Output
Before swap, value of a : 10 Before swap, value of b : 20 After swap, value of a : 20 After swap, value of b : 10
Explanation
- The `swap()` function takes two pointer arguments: `int *x` and `int *y`.
- The values pointed to by `x` and `y` are swapped using a temporary variable `temp`.
- Since the addresses of `a` and `b` are passed to the function, their original values are modified.
- This demonstrates the concept of call by reference in C.
Note: You can modify the program to accept user input values for `a` and `b` instead of using fixed ones.
Codecrown