C Program to Swap 2 numbers without using a Temporary Variable

Hello friends, In this post, I want to share with you C program codes for swapping 2 numbers without using any temporary variable.

This can be done using some simple mathematical formulae based procedure which is given as follows:


a=a+b
b=a-b
a=a-b
Output

You can find the C source code for this program below:



/*
C program to swap 2 variables without using a temporary variables
Author:   http://www.123mylist.com
*/
#include<stdio.h>
#include<conio.h>
int main()
{
    float a,b;
    printf("Program to Swap 2 numbers without using Temporary Variable\nEnter the First Value:\n");
    scanf("%f",&a);
    printf("Enter the Second Value:\n");
    scanf("%f",&b);
    printf("\nBefore Swapping\na = %0.2f\nb = %0.2f",a,b);
    a=a+b;
    b=a-b;
    a=a-b;
    printf("\n\nAfter Swapping\na = %0.2f\nb = %0.2f",a,b);
    
    getch();
    return 0;
}