Programming Examples
C program to Swap Numbers Without Using Temporary Variables
Write a C program to Swap Numbers Without Using Temporary(3rd) Variables
Solution
#include <stdio.h>
int main() {
double a, b;
printf("Enter a: ");
scanf("%lf", &a);
printf("Enter b: ");
scanf("%lf", &b);
// Swapping
// a = (initial_a - initial_b)
a = a - b;
// b = (initial_a - initial_b) + initial_b = initial_a
b = a + b;
// a = initial_a - (initial_a - initial_b) = initial_b
a = b - a;
printf("After swapping, a = %.2lf\n", a);
printf("After swapping, b = %.2lf", b);
return 0;
}
Output
Enter a: 10.25
Enter b: -12.5
After swapping, a = -12.50
After swapping, b = 10.25