c-programs-basics
In this c program, we will get two numbers from the user and swap the values, meaning if A and B are two variables having the values 15 and 25 Respectively. After Swapping the Numbers, the values will change to A = 25 and B = 15.
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 :


Output-Swap-Two-Numbers-Using-Third-Variable














How Swapping Works!

Swapping Of Two Numbers








(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 :
Output-C-Program-To-Swap-Two-Numbers








In this way, you can perform swapping of two numbers in c, you can also do the same program without using a third variable.