Swapping two numbers

Two numbers can be swapped or interchanged. It means first number will become second and second number will become first.

For example

There are two methods for swapping:

  • By using third variable.
  • Without using third variable.

Swapping Using Third Variable

Swap two numbers 45 and 78 using a third variable.

Example:

Output:

PHP Swapping two numbers 1

Swapping Without using Third Variable

Swap two numbers without using a third variable is done in two ways:

  • Using arithmetic operation + and ?
  • Using arithmetic operation * and /

Example for (+ and -):

Output:

PHP Swapping two numbers 2

Example for (* and /):

Output:

PHP Swapping two numbers 3



Latest Courses