Friday, March 29, 2024
HomejQuery4 Methods to Swap Numbers in C++ {Perform, temp variable, mathematic}

4 Methods to Swap Numbers in C++ {Perform, temp variable, mathematic}


Tips on how to swap numbers in C++ program?

On this tutorial, we’ll present you easy methods to swap numbers in C++ within the following methods:

  • By utilizing the swap() bulit-in operate
  • By utilizing the non permanent variable
  • Utilizing + and –
  • Utilizing * and /

First Manner – Utilizing a built-in swap operate

C++ Customary Template Library has a built-in operate (std::swap) that you could be use to swap two numbers.

You merely present two numbers to swap() operate i.e.

swap(x, y);

On this manner, you don’t want a 3rd variable.

An instance of utilizing the C++ swap operate

The instance beneath reveals utilizing the swap() operate to interchange two variable values through the use of swap() operate:



Output:

CPP-swap-function

Taking person enter for swapping two numbers program

On this program, the person is requested to enter two numbers to be swapped.

  • The primary entered quantity is assigned to variable x.
  • The second quantity is assigned to the variable y.
  • The swap() operate is used
  • The swapped numbers are displayed as follows:



A pattern output:

CPP-swap-input

Second manner: Utilizing a short lived third variable approach to swap numbers

Because the goal is to swap two variable values. We will use the third variable to briefly maintain the primary variable worth.

Then copy the contents of the second variable to first

Lastly copy the contents of the third variable (non permanent) to the second variable.

See this in motion beneath:



Pattern Output:

CPP-swap-temp-variable

In this system,

  • The person is requested to 2 numbers to swap
  • Numbers are assigned to variables x and y
  • A brief variable z is used to carry the worth of x

Swap numbers with out a third variable by + and –

On this approach, we’ll carry out addition and subtraction to swap the numbers of two variables.

Suppose:

x= 10;

y= 20

x = x + y = 30

y = x – y i.e. (30-20) = 10

x = x – y i.e. (30 – 10) = 20

Completed?

Allow us to see this in C++ program:



A pattern output:

Utilizing * and / for quantity swapping instance

You might also use the division and multiplication in an effort to swap numbers with out utilizing the built-in swap operate or a 3rd non permanent variable.

Once more, allow us to suppose:

x = 10

y = 20

The logic to attain the result’s:

x = x * y:  (10*20)= 200

y = x/y: (200/20) = 10

x = x/b : (200/10)  = 10

Swapped?

C++ program to swap by /* approach



Pattern output as we entered two numbers:

CPP-swap-multiply-divide

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments