Write a program in C to swap two numbers using third variable

This is a common question asked in various interviews and in assignments given to the student to write a program in c to swap two numbers using the third variable. Here, in the solution, we will take two numbers from the user and store them in variable a and b. Then, we will use the temporary variable temp to swap the numbers stored in this variables. Lets see the solution:

#include
#include
void main()
{
   int a, b, temp;
   printf("Enter the two numbers to swap\n");
   scanf("%d%d", &a, &b);
 
   printf("Before Swapping\na = %d\nb = %d\n",a,b);
   //Logic of Swapping of numbers by using third variable.
   temp = a;
   a = b;
   b = temp;
 
   printf("After Swapping\na = %d\nb = %d\n",a,b);
   getch();
}

Examples

Output of the C program to swap two numbers using third variable