Friday, 27 December 2013

swap two variable in C

Q: Swap two variables in C?

1. Using Temporary Variable

#include <stdio.h>

int main(int argc, char *argv[]){
    int temp,num1,num2;
    printf("Enter Two Number: ");
    scanf(" %d %d", &num1, &num2);
    printf("Before Swap num1=%d and num2=%d\n", num1, num2);
    temp = num1;
    num1 = num2;
    num2 = temp;
    printf("After Swap num1=%d and num2=%d\n", num1, num2);
    return 0;
}
2. Not Using Temporary Variable

#include <stdio.h>

int main(int argc, char *argv[]){
    int num1,num2;
    printf("Enter Two Number: ");
    scanf(" %d %d", &num1, &num2);
    printf("Before Swap num1=%d and num2=%d\n", num1, num2);
    num1+=num2;
    num2 =num1-num2;
    num1 = num1-num2;
    printf("After Swap num1=%d and num2=%d\n", num1, num2);
    return 0;
}
/***********************************
* NOTE MEMORY OVER FLOW CAN HAPPEN *
***********************************/
3. Not Using Temporary Variable/Using Bitwise operator

#include <stdio.h>

int main(int argc, char *argv[]){
    int num1,num2;
    printf("Enter Two Number: ");
    scanf(" %d %d", &num1, &num2);
    printf("Before Swap num1=%d and num2=%d\n", num1, num2);
    num1^=num2;
    num2^=num1;
    num1^=num2;
    printf("After Swap num1=%d and num2=%d\n", num1, num2);
    return 0;
}
4. Using Bitwise operator and input From Command Line

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
    int num1; 
    int num2;
    if(argc != 3){
        printf("\nUSAGE:: %s <num1> <num2>\n",argv[0]);
        exit(-1);
    }
    num1 = atoi(argv[1]);
    num2 = atoi(argv[2]);
    printf("Before Swap num1=%d and num2=%d\n", num1, num2);
    num1^=num2;
    num2^=num1;
    num1^=num2;
    printf("After Swap num1=%d and num2=%d\n", num1, num2);
    return 0;
}

No comments:

Post a Comment