Swap the values of two Integers using C programming.

  • Swap using 3rd variable :-



Program :

#include<stdio.h>
#include<conio.h>
void main()
{ int a,b,c;
clrscr();
printf("Enter the value of a\n");
scanf("%d",&a);
printf("Enter the value of b\n");
scanf("%d",&b);
printf("Before swapping a=%d, b=%d\n",a,b);
c=a;
a=b;
b=c;
printf("After swapping a=%d, b=%d",a,b);
getch();


}

Output :


  • Swap without using 3rd variable :-


Program :

#include<stdio.h>
#include<conio.h>
void main()
{ int a,b;
clrscr();
printf("Enter the value of a\n");
scanf("%d",&a);
printf("Enter the value of b\n");
scanf("%d",&b);
printf("Before swapping a=%d, b=%d\n",a,b);
a=a+b;
b=a-b;
a=a-b;
printf("After swapping a=%d, b=%d",a,b);
getch();


}

Output :



Comments