C Program to Swap Two Numbers without using Temporary Variable

@codevarsity
 · 
1.3k views
 · 

This program showcases the way to swap two numbers without using a temporary variable.

Code

#include <stdio.h>
int main()
{
    double firstNumber, secondNumber;

    printf("Enter first number: ");
    scanf("%lf", &firstNumber);

    printf("Enter second number: ");
    scanf("%lf",&secondNumber);

    // Swapping process

    firstNumber = firstNumber - secondNumber;
    secondNumber = firstNumber + secondNumber;
    firstNumber = secondNumber - firstNumber;

    printf("\nAfter swapping, firstNumber = %.2lf\n", firstNumber);
    printf("After swapping, secondNumber = %.2lf", secondNumber);

    return 0;
}

Output

Enter first number: 10.25
Enter second number: -12.5

After swapping, firstNumber = -12.50
After swapping, secondNumber = 10.25

Comments