Three methods and simple analysis of switching Variables

Source: Internet
Author: User

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

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.