Swapping Of Two Numbers In C Using A Third Variable
#include<stdio.h> #include<conio.h> void main() { int a,b,temp; clrscr(); printf("\n Type any two numbers to swap:\n "); printf("\n A = "); scanf("%d",&a); printf("\n B = "); scanf("%d",&b); printf("\n Numbers before swapping \n"); printf("\n A = %d \t B = %d",a,b); temp=a; a=b; b=temp; printf("\n\n Numbers after swapping\n"); printf("\n A = %d \t B = %d",a,b); getch(); }
Output :
How Swapping Works!
(Image source: tutorial4us.com)
(Image source: tutorial4us.com)
- We use a temporary variable along with two variables A and B.
- The logic behind this is easy. We will interchange the values in-between the variables.
- As the temp variable have no value in it, we'll first move the value from A into temp variable.
- Then We'll Move the value from B to A and then again the value we stored in temp into B.
This way the values of A and B gets swapped.
C Program to Swap Two Numbers in Dev C++
#include<stdio.h> int main() { int a,b,temp; printf("\n Type any two numbers to swap:\n "); printf("\n A = "); scanf("%d",&a); printf("\n B = "); scanf("%d",&b); printf("\n Numbers before swapping \n"); printf("\n A = %d \t B = %d",a,b); temp=a; a=b; b=temp; printf("\n\n Numbers after swapping\n"); printf("\n A = %d \t B = %d",a,b); getch(); return 0; }
Output :
In this way, you can perform swapping of two numbers in c, you can also do the same program without using a third variable.