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

C Language Examples - Swap Two Numbers

C Language Examples - Swap Two Numbers

C Language Examples C Language Examples

Using a temporary variable

The following example demonstrates swapping the values of two floating-point numbers.

Example

#include

<

stdio.h

int

main

(

)

{

double

firstNumber

,

secondNumber

,

temporaryVariable

;

printf

(

"

Enter the first number:

"

)

;

scanf

(

"

%lf

"

, &

firstNumber

)

;

printf

(

"

Enter the second number:

"

)

;

scanf

(

"

%lf

"

,&

secondNumber

)

;

// Assign the value of the first number to temporaryVariable

temporaryVariable

=

firstNumber

;

// Assign the value of the second number to firstNumber

firstNumber

=

secondNumber

;

// Assign temporaryVariable to secondNumber

secondNumber

=

temporaryVariable

;

printf

(

"

\

nAfter swapping, firstNumber = %.2lf

\

n

"

,

firstNumber

)

;

printf

(

"

After swapping, secondNumber = %.2lf

"

,

secondNumber

)

;

return

0

;

}

Running result:



输入第一个数字: 1

输入第二个数字: 2



交换后, firstNumber = 2.00

交换后, secondNumber = 1.00

Without a temporary variable

Swap two integers without using a temporary variable:

Example

#include

<

stdio.h

int

main

(

)

{

int

a

,

b

;

a

=

11

;

b

=

99

;

printf

(

"

Before swapping -

\

n a = %d, b = %d

\

n

\

n

"

,

a

,

b

)

;

a

=

a

b

;

// (11 + 99 = 110) At this point, a holds the sum of the two numbers, and b is unchanged

b

=

a

b

;

// ( 110 - 99 = 11)

a

=

a

b

;

// ( 110 - 11 = 99)

printf

(

"

After swapping -

\

n a = %d, b = %d

\

n

"

,

a

,

b

)

;

}

Running result:



交换之前 - 

 a = 11, b = 99 



交换后 - 

 a = 99, b = 11 

C Language Examples C Language Examples