Program to Swap two Numbers without temp or third variable

Program to swap two numbers without temp or third variable are very important in terms of interview. In swapping we exchange the position of two numbers. There are multiple ways in which you can swap two numbers . Some of them are

Write a Program to Swap two numbers using third variable.

Swap two numbers using Bitwise XOR Operator


Approach for Swap two Numbers without temp or third variable

Let’s say we have two numbers a and b. We need to swap these two numbers without using any temp or third variable.

Subscribe Our Tutorials

Get Latest Updates on Facebook

Step 1 – Add the value of a and b then assign the sum to variable a.

Step 2 – Subtract the value of variable a and b and assign it to variable b.

Step 3 –¬†Subtract the value of variable a and b and assign it to variable a.

 

Let’s check this approach. Suppose the value of a is 3 and b is 4.

Now we get the output a = 4 and b = 3.

Program to Swap Two Numbers without temp or third variable

PHP Code to Swap Two Numbers without temp or third Variable

WebRewrite

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.
Tagged , , , . Bookmark the permalink.