Swap Two Numbers in C

Swap Two Numbers in C


Swap Two Numbers In C Programming In Different Ways

In C ProgrammingDecember 2, 20182204 Views Smita Debata

Swapping means interchanging.

Let’s consider two variables x=10 & y=20. After swapping it will become x=20 and y=10.Here x & y value’s are interchanged.

   

There are various methods to swap two numbers. Here we are going to discuss some of the methods.

  • Swapping of two numbers with using a third variable.
  • Swapping of two numbers without using third/temp variable.
  • Swapping of two numbers using bit-wise XOR operator.
  • Swapping of two numbers using pointer.
  • Swapping of two numbers using function.

1. Swapping Of Two Numbers With Using a Third Variable.

To swap two numbers using third variable we have to declare a temp variable.

 

temp=x; //contains of x will be assigned to temp

Again y value we will assign to x .x value will be replaced with y value.

x=y;