How to swap without third variable?

A variable is a named location in memory that is used to store data which can be modified in a program. Let us see how to swap two variables without using third variable. This can be done in number of namely


  • By using arithmetic operators

  • By using Bitwise operators

  • By using Pointers Concept and so on


Let us see one of the method namely by using arithmetic operators.
Consider 2 variables say x=50 and y=70 and let us see how to swap the value of two variables that is make x=70 and y=50 without using third variable. This can be done by using following arithmetic operations namely

x= x + y

y= x - y

x= x - y


Which gives

  • x= x + y gives x= 70 + 50 an so x is equal to 120

  • y= x - y gives y = 120 - 70 which makes the value of y as 50

  • x= x - y gives x= 120 - 50 and thus value of x becomes 70


Thus value of x and y gets swapped without using third variable and the whole program is given below:

main()

{

int x=50,y=70;

x= x + y;

y= x - y;

x= x - y;

printf(“x=%d y=%d”, x,y);

}


This program gives output as
x=70 y=50

Questions by GeekAdmin   answers by GeekAdmin

Showing Answers 1 - 9 of 9 Answers

Ramya Shetty

  • Nov 11th, 2015
 

a and b are two variables ; Following code will swap both number and string inputs
a = Inputbox("Enter a")
b = Inputbox("Enter b")
a = a + b
b = left(a,(instr(a,b)-1))
a = Right(a,(len(a)-len(b)))
msgbox "b ="&b
msgbox "a = "&a

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions