Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C++ Example - Swap Two Numbers

C++ Example - Swap Two Numbers

C++ Example C++ Example

Below we use two methods to swap two variables: with a temporary variable and without a temporary variable.

Example - using a temporary variable

include

<

iostream

using

namespace

std

;

int

main

(

)

{

int

a

=

5

,

b

=

10

,

temp

;

cout

<<

"

Before swapping:

"

<<

endl

;

cout

<<

"

a =

"

<<

a

<<

"

, b =

"

<<

b

<<

endl

;

temp

=

a

;

a

=

b

;

b

=

temp

;

cout

<<

"

\n

After swapping:

"

<<

endl

;

cout

<<

"

a =

"

<<

a

<<

"

, b =

"

<<

b

<<

endl

;

return

0

;

}

The output of the above program is:



Before swapping:

a = 5, b = 10



After swapping:

a = 10, b = 5

Example - without a temporary variable

include

<

iostream

include

<

iostream

using

namespace

std

;

int

main

(

)

{

int

a

=

5

,

b

=

10

;

cout

<<

"

Before swapping:

"

<<

endl

;

cout

<<

"

a =

"

<<

a

<<

"

, b =

"

<<

b

<<

endl

;

a

=

a

b

;

b

=

a

b

;

a

=

a

b

;

cout

<<

"

\n

After swapping:

"

<<

endl

;

cout

<<

"

a =

"

<<

a

<<

"

, b =

"

<<

b

<<

endl

;

return

0

;

}

The output of the above program is:



Before swapping:

a = 5, b = 10



After swapping:

a = 10, b = 5

C++ Example C++ Example