Saturday, December 21, 2013

Swap two values

Write a C program to interchange values of two numbers.
#include <stdio.h>

int main(){
    int X, Y, Z;
  
    /*Using third variable Z*/
    X = 5;
    Y = 10;
    Z = X;
    X = Y;
    Y = Z;
    printf("X:%d Y:%d\n", X, Y);

    /*Without using third variable Z*/
    X = 5;
    Y = 10;
    X = X + Y;
    Y = X - Y;
    X = X - Y;
    printf("X:%d Y:%d\n", X, Y);
  
    /*Using bitwise operation*/
    X = 5;
    Y = 10;
    X = X ^ Y;
    Y = X ^ Y;
    X = X ^ Y;
    printf("X:%d Y:%d\n", X, Y);
  
    /*char swap using bitwise operation*/
    char x = 'x';
    char y = 'y';
    x = x ^ y;
    y = x ^ y;
    x = x ^ y;
    printf("x:%c y:%c\n", x, y);
    /*char swap using bitwise operation*/
    long a = 123456;
    long b = 654321;
    a = a ^ b;
    b = a ^ b;
    a = a ^ b;
    printf("a:%ld b:%ld\n", a, b);

    return 0;
}

No comments:

Post a Comment