C Language Example - Swapping the Values of Two Numbers
Use 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;
}
Run result:
输入第一个数字: 1 输入第二个数字: 2 交换后, firstNumber = 2.00 交换后, secondNumber = 1.00
Without using a temporary variable
Swap the values of 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 time, variable a is the sum of the two numbers, and b has not changed.
b = a - b; // ( 110 - 99 = 11)
a = a - b; // ( 110 - 11 = 99)
printf("After swapping -\n a = %d, b = %d \n", a, b);
}
Run result:
交换之前 - a = 11, b = 99 交换后 - a = 99, b = 11other extensions
C Language Examples