Become Our Fan on Social Sites!

Facebook Twitter

Google+ RSS YouTube

Tuesday, 24 September 2013

swapping or interchange values of two variables in c language

1) Swapping using temporary variable in c language



#include<stdio.h>
int main()
{
    int x, y, temp;
   
    printf("Enter the value of x and y :");
    scanf("%d %d", &x, &y);
    printf("\nBefore swapping x=%d, y=%d \n", x, y);
   
    /* Swapping logic */
     temp = x;
     x = y;
    y = temp;

    printf("After swapping x=%d, y=%d", x, y);
   
    return 0;
}


2) Swapping without temporary variable in c language

#include <stdio.h>
int main()
{
    int x, y;
  
    printf("Enter values of x and y: ");
    scanf("%d %d", &x, &y);
    printf("Before swapping x=%d, y=%d", x,y);

    /*Swapping logic */
     x = x + y;
     y = x - y;
     x = x - y;
   
    printf("After swapping x=%d y=%d", x, y);
    return 0;
}


3) Swapping variables using Bitwise operator in c language 

#include<stdio.h>
#include<conio.h>
void main()
{
    int x, y;
    clrscr();
    printf("Enter values of x and y : ");
    scanf("%d %d",&x,&y);
    printf("\n\nBefore swapping x=%d y=%d",x,y);

    /* Swapping Logic */
    x = x ^ y;
    y = y ^ x;
    x = x ^ y;

    printf("\nAfter swapping x=%d y=%d",x,y);
    getch();
}



0 comments :

Post a Comment