Here we have two methods to swap variables first one is swapping variables with using third variable and second one is swapping variable without using third variable. So following is the program which performs both types of swapping.

#include<stdio.h>

#include<conio.h>

void swap1(int,int);

void swap2(int,int);

void main()

{

int a,b;

clrscr();

printf(“Enter the values for a & b respectively:”);

scanf(“%d%d”,&a,&b);

swap1(a,b);

swap2(a,b);

getch();

}

void swap1(int a,int b)

{int c;

printf(“\n Swap using third variable:”);

c=a;

a=b;

b=c;

printf(“\n After swapping, value of a is %d & value ofb is %d”,

a,b);

}

void swap2(int a, int b)

{

printf(“\n Swap without using third variable:”);

a=a+b;

b=a-b;

a=a-b;

printf(“\n After swapping,value of a is %d & value of b is %d “,a,b);

}

Output:

Enter the values for a&b respectively:

5 8

Swap using third variable

After swapping value of a is 8 and value of b is 5

Swap without using third variable

After swapping value of a is 8 and value of b is 5

let’s have an explanation for this code “-

first of all in main function we are taking values from user and then passing it to function swap1 i.e. swapping with third variable and swap2 which is not using third variable for swapping.

**void swap1**

here first lets say value of a and b are 5 and 8 respectively. Now after assigning value a to c, c = 5.

In the next step we have a = b which makes a=8

and then in next step b = c which will make b = 5 i.e a and b swapped their values.

**void swap2**

again lets say value of a and b are 5 and 8 respectively. now in first step we have a = a+b which makes a = 5+8 =13

In the next step b = a-b that means b = 13 – 8 =5

Last steps says a = a-b which means a = 13 – 5 = 8. This means values are swapped.