Can someone explain to me?

Can someone explain the coding in bold to me? I don't understand how to get 40 10 20 30.

public class Rotater {

public static void main(String[] args) {

int a = 10, b = 20, c = 30, d = 40;

int temp;

temp = d;

d = c;

c = b;

b = a;

a = temp;

System.out.println("before rotation: 10 20 30 40");

System.out.println("after rotation: " + a + " " + b + " " + c + " " + d);

}

}

Re: Can someone explain to me?

Hello unleashed-my-freedom!

What is your question? You use the **temp** variable to rotate the values of your "basic" variables (**a,b,c,d**). So, you give every variable the value of the next (or previous) variable* . The additional variable (**temp**) is used for keeping the first basic variables's value and don't loose it.

*in your case *next* and *previous* don't have an actual meaning because the variables are not ordered but suppose they are (**a-b-c-d**)

Hope I was clear.

Re: Can someone explain to me?

At first, I had 10 20 30 40

But the temp, I had 40 10 20 30.

So you mean if I use temp, the number will (in this case) increase by 1 position?

Re: Can someone explain to me?

After the rotation the values have moved one step forward with the last value going to the first variable (like a cycle).

Code :

after initialization
a b c d temp
10 20 30 40 -
temp = d;
a b c d temp
10 20 30 40 40
d = c;
a b c d temp
10 20 30 30 40
c = b;
a b c d temp
10 20 20 30 40
b = a;
a b c d temp
10 10 20 30 40
a = temp;
a b c d temp
40 10 20 30 40

Hope this helps.

Re: Can someone explain to me?

so we use temp just to increase the order by 1?

Re: Can someone explain to me?

Quote:

Originally Posted by

**unleashed-my-freedom**
so we use temp just to increase the order by 1?

We use temp because otherwise you would loose a value. Think like you have two cups (A and B) in two positions (1 and 2 respectively) that each of them can place __only one__ cup and you can carry only one cup in your hands. Now, if you want to exchange positions between cups you start like this:

take cup A and put it in position 1. But then you have to throw away cup B(because you can't have two cups in you a position or in your hands).

Therefore you need a new assisting position (3).

Then you put

1) cup A to position 3 - now position 1 is empty

2) cup B to position 1 - now position 2 is empty

3) cup A to position 2

So, **temp** is the assisting position.

Hope that makes sense. :o