GeekInterview.com
  I am new, Sign me up!
 
Home C
 

Swap two variables

 
Category: C
Comments (1)


How to swap two variables without using 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 learn how to swap two variables without using third variable. This can be done in number of ways


  • By using arithmetic operators
  • By using Bitwise operators
  • By using Pointers Concept and so on

One of the method is by using arithmetic operators. Consider 2 variables say x=50 and y=70. To swap the value of two variables that is make x=70 and y=50 without using third variable can be done by using following arithmetic operations


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



Read Next: Precedence of Operators



 
Related Topics


 

Comments


Teacher said:

  nice code thanks.
October 21, 2008, 12:58 pm

Post Your Comment:

Members Please Login
Your Name:*
e-mail ID:(required for notification)*
Image Verification: 
 
 Subscribe    

Sponsored Links

 
About Us -  Privacy Policy -  Terms and Conditions -  Contact  

Copyright © 2005 - 2009 GeekInterview.com. All Rights Reserved

Page copy protected against web site content infringement by Copyscape