Wednesday, December 30, 2015

C Program to swap two numbers without using a temporary variable

C Program to swap two numbers without using a temporary variable
First Method
#include <stdio.h>
int main(void) {
    int a=3,b=6;
    a = a + b; // a = 9
    b = a - b; // b = 3
    a = a - b; // a = 6
    printf("a=%d,b=%d",a,b);
    return 0;
}

Second Method (using XOR operator)
#include <stdio.h>
int main(void) {
    int a=3,b=6;
    a = a ^ b; // a = 5
    b = a ^ b; // b = 3
    a = a ^ b; // a = 6
    printf("a=%d,b=%d",a,b);
    return 0;
}
Note: Binary XOR Operator copies the bit if it is set in one operand but not both.
  a = 3 = 011
  b = 6 = 110
-------------
a^b = 5 = 101

Third Method
#include <stdio.h>
int main(void) {
    int a=3,b=6;
    a = a * b; // a = 18
    b = a / b; // b = 3
    a = a / b; // a = 6
    printf("a=%d,b=%d",a,b);
    return 0;
}

No comments:

Post a Comment