Program to swap variable’s numeric values

Program to swap variable’s numeric values

 

Consider the following program in which we will swap the values of two variables:

CODE:

# include <stdio. h>

# include <conio. h>

void main ()

{

   int x = 15, y = 25, temp;

   temp = x;

   x = y;

   y = temp;

   printf (“x= %d and y= %d”, x, y);

   getch();

}

OUTPUT:

x = 25 and y = 15

 

Program to swap two numbers without using third variable:

Consider the following code in which we have swapped two numbers without using a third variable:

CODE:

# include <stdio. h>

# include <conio. h>

void main ()

{

   int x = 15, y = 25;

   x = x + y – (y = x);

   printf (“x= %d and y= %d”, x, y);

   getch ();

}

OUTPUT:

x = 25 and y = 15

 

Program to swap two numbers using bitwise operator:

Consider the following code in which we have swapped two numbers by using bitwise operator:

CODE:

# include <stdio. h>

# include <conio. h>

void main ()

{

   int x = 15, y = 25;

   x = x ^ y;

   y = x ^ y;

   x = x ^ y;

   printf (“x = %d and y = %d”, x, y);

   getch ();

}

OUTPUT:

x = 25 and y = 15

 

Program to swap two numbers using division and multiplication:

Consider the following code in which we have swapped two numbers by using division and multiplication:

CODE:

# include <stdio. h>

# include <conio. h>

void main ()

{

   int x = 15, y = 25;

   x = x * y;

   y = x / y;

   x = x / y;

   printf (“x = %d and y = %d”, x, y);

   getch ();

}

OUTPUT:

x = 25 and y = 15