Pages - Menu

Thursday, November 29

Swap Two numbers Using a Temporary Variable

Write a C program to swap two numbers using a temporary variable.
Swapping interchanges the values of two given variables.

step1: temp=x;
step2: x=y;
step3: y=temp;

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.


#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);
temp = a;
a = b;
b = temp;
printf("After swapping a=%d, b=%d", a, b);
return 0;

Enter the values of a and b: 2 3
Before swapping a=2, b=3
After swapping a=3, b=2