Google News
logo
C Program to Swap Two Numbers
Swap two numbers in C programming using two different techniques.

Swap Numbers Using Temporary Variable :

Program :
#include<stdio.h>
int main() {
  double first, second, temp;
  printf("Enter first number: ");
  scanf("%lf", &first);
  printf("Enter second number: ");
  scanf("%lf", &second);

  // value of first is assigned to temp
  temp = first;

  // value of second is assigned to first
  first = second;

  // value of temp (initial value of first) is assigned to second
  second = temp;

  // %.2lf displays number up to 2 decimal points
  printf("\nAfter swapping, first number = %.2lf\n", first);
  printf("After swapping, second number = %.2lf", second);
  return 0;
}
Output :
Enter first number: 6
Enter second number: 9
After swapping, first number = 9.00
After swapping, second number = 6.00
* In the above program, the temp variable is assigned the value of the first variable.

* Then, the value of the first variable is assigned to the second variable.

* Finally, the temp (which holds the initial value of first) is assigned to second.

This completes the swapping process.

Swap Numbers Without Using Temporary Variables :

Program :
#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;

  // %.2lf displays numbers up to 2 decimal places
  printf("After swapping, a = %.2lf\n", a);
  printf("After swapping, b = %.2lf", b);

  return 0;
}​
Output :
Enter a: 3
Enter b: 7
After swapping, a = 7.00
After swapping, b = 3.00