C Program to Swap two numbers

In this article, we are going to learn about how to swap two numbers in C programming. We will learn to do this with the help of multiple techniques. The techniques that we are going to talk about in this article are:

  • By using a Temporary Third Variable.
  • Without using a Temporary Third Variable.

1. How to Swap two numbers By using Third Variable in C lanaguage


In this example, we will make use of a temp variable to swap two numbers. The temp variable is assigned the value of the first variable. Then, the value of the first variable is assigned to the second variable. The temp variable which is holding the first value will be assigned to the second variable. Let us now understand this with the below code example:

#include<stdio.h>
int main() 
{
  int FirstVar, SecondVar, TempVar;

  printf("Please enter the first number: ");
  scanf("%d", &FirstVar);

  printf("Please enter the second number: ");
  scanf("%d", &SecondVar);

  
  TempVar = FirstVar;

  FirstVar = SecondVar;

  SecondVar =  TempVar;

 
  printf("\nAfter swapping, first number Becomes = %d\n", FirstVar);

  printf("After swapping, second number Becomes = %d ", SecondVar);

  return 0;
}

Output

Please enter the first number: 9
Please enter the second number: 6

After swapping, first number Becomes = 6
After swapping, second number Becomes = 9 

2. How to swap two numbers Without using a Temporary Third Variable in C


In this example, we will not make use of a temp variable to swap two numbers. We will use the + and – operators to swap two numbers. Let us now understand this with the below code example:

#include <stdio.h>
int main() 
{

  int FirstVar, SecondVar;

  printf("Please enter the first number: ");
  scanf("%d", &FirstVar);

  printf("Please enter the second number: ");
  scanf("%d", &SecondVar);  

  FirstVar = FirstVar - SecondVar;

  SecondVar = FirstVar + SecondVar;

  FirstVar =  SecondVar - FirstVar;

  printf("\nAfter swapping, first number Becomes = %d\n", FirstVar);

  printf("After swapping, second number Becomes = %d ", SecondVar);

  return 0;
}

output

Please enter the first number: 6
Please enter the second number: 9

After swapping, first number Becomes = 9
After swapping, second number Becomes = 6