# C program to swap two numbers using a temporary third variable.

+1 vote
6,753 views

+1 vote
Example:
if x=5 and y=8, consider a temporary variable temp.
step1: temp=x=5;
step2: x=y=8;
step3: y=temp=5;
Thus the values of the variables x and y are interchanged.

Program:
#include <stdio.h>
int main()
{
int a, b, temp;
printf("Enter the value of a and b: \n");
scanf("%d %d", &a, &b);
printf("Before swapping a=%d, b=%d \n", a, b);

/*Swapping logic */
temp = a;
a = b;
b = temp;

printf("After swapping a=%d, b=%d", a, b);
return 0;
}

Output:
Enter the values of a and b: 2 3
Before swapping a=2, b=3
After swapping a=3, b=2
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;            // a,b and c  are integers
clrscr();        // this is a function that used to clear the previos output
printf("enter any two numbres\n");
scanf("%d%d",&a,&b);
printf("value of a before Swap = %d\n",a);
printf("value of b before Swap = %d\n",b);
/*************Logic to swap***********************/
c=a;      // value of a given to c
a=b;      // value of b given to a
b=c;     // value of c given to b
printf("value of a after Swap = %d\n",a);
printf("value of b after Swap = %d\n",b);

getch();
}
answered by Sr Member (2,730 points)
Swapping interchanges the values of two given variables.

Logic:

step1: temp=x;

step2: x=y;

step3: y=temp;

Example:

if x=5 and y=8, consider a temporary variable temp.

step1: temp=x=5;

step2: x=y=8;

step3: y=temp=5;

Thus the values of the variables x and y are interchanged.

Program:

#include <stdio.h>

int main() {

int a, b, temp;

printf("Enter the value of a and b: \n");

scanf("%d %d", &a, &b);

printf("Before swapping a=%d, b=%d \n", a, b);

/*Swapping logic */

temp = a;

a = b;

b = temp;

printf("After swapping a=%d, b=%d", a, b);

return 0;

}

Output:

Enter the values of a and b: 2 3

Before swapping a=2, b=3

After swapping a=3, b=2