There are two main ways to exchange two variables: With or without temporary variables. There are three simple algorithms for specific operations:
1,Algorithm with temporary variables
#include <stdio.h>int main(void){int a, b, t;scanf("%d%d", &a, &b);t = a;a = b;b = t;printf("a = %d, b = %d\n", a, b);return 0;}
2,Algorithm 1 without temporary variables (
Addition and subtraction)
#include <stdio.h>int main(void){int a, b;scanf("%d%d", &a, &b);a = a + b;b = a - b;a = a - b;printf("a = %d, b = %d\n", a, b);return 0;}
3,Algorithm 2 without using temporary variables (
Exclusive or operation)
#include <stdio.h>int main(void){int a, b;scanf("%d%d", &a, &b);a = a ^ b;b = b ^ a;a = a ^ b;printf("a = %d, b = %d\n", a, b);return 0;}
Summary: in normal use, the algorithm with the help of temporary variables is good enough. Algorithms 1 and 2 that do not use temporary variables look good (with less than one variable), but are rarely used because of its narrow Applicability: this can be done only when the addition, subtraction, or exclusive data types are defined. These two algorithms are only used to improve the ability to read code.
Three methods and simple analysis of switching Variables