Application of pointer variables: input two integers, output from large to small (using pointer variables), integer pointer

Source: Internet
Author: User

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 ;}

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.