Application of pointer variables: input two integers, output from large to small (using pointer variables), integer pointer
How do I operate before I learn the pointer?
Exchange with a temporary variable
# Include <iostream> using namespace std; void sort (int x, int y) {int temp; if (x <y) {temp = x; x = y; y = temp;} cout <x <"" <y <endl;} // point to int main () {int a, B; cout <"enter two integers. "<Endl; cin> a> B; sort (a, B); return 0 ;}
After learning the pointer method, how can I perform this operation?
# Include <iostream> using namespace std; // point to the int main () {int a, B, * p1, * p2, * p; cout <"enter two integers. "<Endl; cin> a> B; p1 = & a; p2 = & B; if (a <B) {p = p1; p1 = p2; p2 = p ;}cout <"a =" <a <"B =" <B <endl; cout <"max =" <* p1 <"min =" <* p2 <endl; return 0 ;}
Use pointers as function parameters to handle sorting from large to small.
# Include <iostream> using namespace std; void swap (int * p1, int * p2) {int temp; temp = * p1; * p1 = * p2; * p2 = temp;} // pointer to an integer: int main () {int a, B, * point1, * point2; cout <"enter two integers. "<Endl; cin> a> B; point1 = & a; B point2 = & B; if (a <B) {swap (point1, point2 );} cout <"max =" <a <"min =" <B <endl; return 0 ;}