I have two variables, $x$ and $y$, and I want to swap their values. (For example, if $x$ has value 5 and $y$ has value "banana", then after the swap I want $x$ to have value "banana" and $y$ to have value 5.) Explain why the code x = y y = x doesn't work, and figure out what we need to do to swap the values of $x$ and $y$.

Respuesta :

Answer:

see explanation below.

Step-by-step explanation:

I have two variables, $x$ and $y$, and I want to swap their values.

For example, if $x$ has value 5 and $y$ has value "banana", then after the swap I want $x$ to have value "banana" and $y$ to have value 5.

1. Explain why the code x = y y = x doesn't work,

2. figure out what we need to do to swap the values of $x$ and $y$.

1. the code x=y means a copy of the y-value ("banana") to x

after this step, both variables x and y will have the value "banana".

Evidently the next step y=x will recopy the copied value of "banana" in x back to y.

Net result, both variables will contain "banana", not an exchange.

2. The code that will work requires a third temporary variable, say t.

We can then do a circular copy, starting with assignment of t.

t=x   (t now contains 5)

x=y  (x now contains "banana")

y=t   (y now contains 5)

Thus the exchange is now complete.

The code x = y y =x doesn't work as the values are duplicated.

To overcome the issue, we will use a temporary variable k, and the code will look like this:

k = x

x = y

y = k.

What is a code?

A code is a set of steps or instructions that help us achieve our target of performing a set of operations over given variables.

How to solve the question?

In the question, we are informed that a person has two variables, $x$, and $y$, and he/she wants to swap the values of these variables.

We are asked to explain why the code,

x = y

y = x

doesn't work.

We are also asked to provide the right code which helps the person swap the values.

The provided code doesn't work, as after the first step (x = y), both x and y have the value stored in y, and in the second step (y = x), x copies the initial value of y to y, which doesn't help them swap values.

Example: x had initially 5, and y had initially "banana".

After the step, x = y, the value of y is copied in x, which makes x = "banana".

Now, in the step, y = x, the then value of x is copied in y, which means x = "banana" is copied to y, making y = "banana" again.

So, in the end, both x and y have "banana", which doesn't help the person swap the values.

For the code to work, we need to add a temporary variable, say k.

We will copy the value of x in k, then the value of y in x, and then the value ok k in y. This will help the person complete the swap between $x$ and $y$.

The code:

k = x

x = y

y = k.

Learn more about coding at

https://brainly.com/question/14290579

#SPJ2

Otras preguntas