C programs to swap two variables without using temporary variable

PROGRAM 1:

#include<stdio.h>
int main()
{
    int a,b;
    printf("Enter values of a and b\n");
    scanf("%d%d",&a,&b);
    printf("Before swaping a=%d b=%d\n",a,b);
    a=a+b;
    b=a-b;
    a=a-b;
    printf("After swapping a=%d b=%d\n",a,b);
    return 0;
}

OUTPUT:

Enter values of a and b
10
20
Before swaping a=10 b=20
After swapping a=20 b=10

PROGRAM 2:

#include<stdio.h>
int main()
{
    int a,b;
    printf("Enter values of a and b\n");
    scanf("%d%d",&a,&b);
    printf("Before swaping a=%d b=%d\n",a,b);
    a=a^b;
    b=a^b;
    a=a^b;
    printf("After swapping a=%d b=%d\n",a,b);
    return 0;
}

OUTPUT:

Enter values of a and b
10
20
Before swaping a=10 b=20
After swapping a=20 b=10

Popular Posts