Learn how to write a C program to swap the values of two variables without using any extra variables. This guide demonstrates how to use arithmetic operations or bitwise XOR to interchange the values of two variables efficiently. The tutorial includes clear explanations and code examples for both methods, making it easy to understand and implement in your C programs.
#include <stdio.h> int main() { int a, b; printf("Enter value of a: "); scanf("%d", &a); printf("Enter value of b: "); scanf("%d", &b); a = a + b; b = a - b; a = a - b; printf("After swapping, value of a = %d\n", a); printf("After swapping, value of b = %d\n", b); return 0; }
Inside the main() function:
- Two integer variables `a` and `b` are declared to store the values entered by the user.
- The user is prompted to enter the values of `a` and `b`.
- Using arithmetic operations, the values of `a` and `b` are swapped without using any extra variable.
- Finally, the swapped values of `a` and `b` are printed to the console.