C language applet --------- Summary of variable exchange, Applet ---------
In all language courses, learning C language is a boring process. In the face of a large piece of unfamiliar and headache code, it is easy to lose patience. Of course, as a beginner of C language, you must start from a small program and gradually learn from each other. The patience child overcomes small difficulties. Slowly, you will discover the pleasure of coding from small programs.
Today, I have summarized several small program examples for variable exchange through my recent study;
(1) Implementation Using pointers
# Include <stdio. h>
Main ()
{
Int a = 5, * m;
Int B = 10, * n;
M = & B;
N = &;
Printf ("% d, % d \ n", * m, * n );
}
(2) using third-party variables for variable exchange
# Include <stdio. h>
Main ()
{
Int a = 5;
Int B = 10;
Int t;
T =;
A = B;
B = t;
Printf ("% d, % d \ n", a, B );
}
(3) variable exchange without using third-party Variables
# Include <stdio. h>
Main ()
{
Int a = 5;
Int B = 10;
A = B-a; // a = 5, B = 10
B = B-a; // B = 5, a = 5
A = a + B;
Printf ("% d, % d \ n", a, B );
}
The principle is to regard a and B as points on the number axis and calculate the distance between two points.
Specific process: in the first sentence "a = B-a", find the distance between the two points of AB and save it in; in the second sentence, "B = B-a", find the distance from a to the origin (the difference between the distance from B to the origin and the distance between B and AB) and save it in B; in the third sentence "a = B + a", find the distance from B to the origin (the sum of the distance between a and AB) and save it in. Complete the exchange.
Do you think this short mini-program is very simple? You can write and run it in your own editing environment. After getting familiar with it, you can continue to expand it, not only are two integer variables, but also can be extended to multiple variables. You can also write a function and use it to call it.