Jump to content

How to swap two numbers without using any other variable or function in C++?


SubhanUllah

Recommended Posts

For numbers its pretty easy. Addition is reversible. For other types of data, not to much:

#include <cstdio> 
int main() { 
    int a = 123; 
    int b = 44; 
    float c = -2.234; 
    float d = 4.456; 
    printf("%-18s %11s %14s\n"," ","a  <->  b","c  <->  d"); 
    printf("%-15s %7d\t%7d\t%7.3f\t%7.3f\n","Starting values",a,b,c,d); 
    a = a + b; // a has both numbers 
    c = c + d; // c now is both numbers 
    printf("%-15s %7d\t%7d\t%7.3f\t%7.3f\n","a = a + b",a,b,c,d); 
    b = a - b; // b now has a 
    d = c - d; // d now has c 
    printf("%-15s %7d\t%7d\t%7.3f\t%7.3f\n","b = a - b",a,b,c,d); 
    a = a - b; // a now has b 
    c = c - d; // c now had d 
    printf("%-15s %7d\t%7d\t%7.3f\t%7.3f\n","a = a - b",a,b,c,d); 
} 
Output:

                     a  <->  b      c  <->  d 
Starting values     123            44        -2.234         4.456 
a = a + b           167            44         2.222         4.456 
b = a - b           167           123         2.222        -2.234 
a = a - b            44           123         4.456        -2.234 

 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...