Try   HackMD

Swapping two variables

Question

When you are programming, you will write something like

x = ___ y = ___ z = x # store value of x in z x = y # put value of y in x y = z # restore value of x in y

to swap the values of two variables x and y . What is you are out of memory and cannot declare a new variable z , are you able to do it?

Experiments

You need: handout

  1. Pick two positive integers from
    0511
    as x and y .
  2. Follow the steps on the handout to keep track of x and y .
  3. Think about why this work.
  4. Think about how to use row operations to obtain
    [0110]
    from
    [1001]
    without swapping.

Intuition

Although we say there are three rules for row operations, but Rule 1 can actually be replaced by a sequence of Rule 2 and Rule 3 . Using this idea, one may obtain the algorithm for swapping two variables.

More questions to think about

  1. In C language, an int variable can only handle integers from
    3276832767
    . Adding big numbers, as we did in the algorithm, can potentially cause integer overflow. How can we deal with this issue?

Resources

  1. YouTube: Field Definition (expanded) - Abstract Algebra by Socratica