Introduction
In this tutorial, you’ll learn how to exchange the values of two variables in C using a function. This is done by using call by reference, which allows us to modify the original values of variables from within a function.
C Program to Exchange Values of Two Variables Using Function
#include <stdio.h>
void Exchange(int *a, int *b) {
int temp;
temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x, y;
printf("Enter value of x: ");
scanf("%d", &x);
printf("Enter value of y: ");
scanf("%d", &y);
printf("Before Exchange: x = %d, y = %d\n", x, y);
Exchange(&x, &y);
printf("After Exchange: x = %d, y = %d\n", x, y);
return 0;
}
Explanation
- The
Exchange
function takes two pointers as arguments. - It uses a temporary variable to swap the values of
*a
and*b
. - In
main()
, we pass the addresses ofx
andy
to theExchange
function. - This demonstrates call by reference, allowing us to modify the original variables.
Sample Output
Enter value of x: 5
Enter value of y: 10
Before Exchange: x = 5, y = 10
After Exchange: x = 10, y = 5
Use Cases
- Fundamental example of using pointers and call by reference in C.
- Basis for more advanced topics like swapping values in sorting algorithms.
- Important in interview questions and academic assignments.