How to exchange two numbers

In general, to exchange two numbers, we define intermediate variables to exchange the values ​​of two numbers. This is also the simplest and easy to understand method. But is it possible to exchange two numbers without using intermediate variables? The answer is yes.

First of all, let's talk about the method of introducing intermediate variables.

code show as below:

#include<stdio.h>
int main()
{
    
    
	int a=10;
	int b=20;
	int tmp=a;
	a=b;
	b=tmp;
	printf("%d %d\n",a,b);   
	return 0;
}

The results are as follows:

Insert picture description here

Method 2: (similar to mathematical operations)

(1) The code is as follows:

#include<stdio.h>
int main()
{
    
    
	int a=10;
	int b=20;
	a=a-b;
	b=a+b;
	a=b-a;
	printf("%d %d\n",a,b);
	return 0;
}

The results are as follows:

Insert picture description here

(2) Method two:

code show as below:

#include<stdio.h>
int main()
{
    
    
	int a=10;
	int b=20;
	a=a+b;
	b=a-b;
	a=a-b;
	/*a=a-b;
	b=a+b;
	a=b-a;*/
	printf("%d %d\n",a,b);
	return 0;
}

The results are as follows:

Insert picture description here

Method three (I haven't figured it out yet, but general problems can be solved correctly):

The procedure is as follows:

#include<stdio.h>
int main()
{
	int a=10;
	int b=20;
	a=a^b;
	b=a^b;
	a=a^b;
	printf("%d %d\n",a,b);
	return 0;
}

The results are as follows:

Insert picture description here
Personally think method one is simple and easy to understand.
I hope to help you;

Guess you like

Origin blog.csdn.net/Gunanhuai/article/details/88920346