Home » Blog » Swapping Of Two Numbers Using Temporary Variable, Without Temp Variable, Using Bitwise Operator, Using Multiplication And Division

Swapping Of Two Numbers Using Temporary Variable, Without Temp Variable, Using Bitwise Operator, Using Multiplication And Division

Swapping means change the value of two variables with one another. There is basically four ways to perform swapping that are listed below.

  1. Using Temporary Variable
  2. Without Using Temporary Variable
  3. Using Bitwise Operator
  4. Using Multiplication And Division
  • Using Temporary Variable

In this, the anothe temporary variable is used. The value of first variable is assign to temporary variable. Then the value of second variable is assign to first and value of temporary variable is assign to second variable.

#include<stdio.h>
#include<conio.h>

void main()
{
    int x = 10, y = 15, temp;
    clrscr();

    temp = x;
    x = y;
    y = temp;

    printf("x = %d and y = %d", x, y);
    getch();
}

OutPut

x = 15 and y = 10
  • Without Using Temporary Variable
#include<stdio.h>
#include<conio.h>

void main()
{
    int x = 10, y = 15;
    clrscr();

    x = x + y - (y = x);

    printf("x = %d and y = %d",x,y);
    getch();
}

OutPut

x = 15 and y = 10
  • Using Bitwise Operator
#include<stdio.h>
#include<conio.h>

void main()
{
    int x = 6, y = 4;
    clrscr();

    x = x^y;
    y = x^y;
    x = x^y;

    printf("x = %d and y = %d", x, y);
    getch();
}

OutPut

x = 4 and y = 6
  • Using Multiplication And Division
#include<stdio.h>
#include<conio.h>

void main()
{
    int x = 6, y = 4;
    clrscr();

    x = x*y;
    y = x/y;
    x = x/y;

    printf("x = %d and y = %d", x, y);
    getch();
}

OutPut

x = 4 and y = 6

 

Leave a Reply

Your email address will not be published.