-1

I am given int[][] Science, int rowOne and int rowTwo. How can I swap rowOne and rowTwo?

I know that I am supposed to hold one row in temp variable, but I do not understand how it works. How does temp work?

Chris Martin
  • 29,484
  • 8
  • 71
  • 131
JavaB
  • 95
  • 1
  • 9
  • 5
    Possible duplicate of [How to write a basic swap function in Java](http://stackoverflow.com/questions/3624525/how-to-write-a-basic-swap-function-in-java) – azurefrog Jan 10 '16 at 04:40
  • I still do not know how to do it @azurefrog – JavaB Jan 10 '16 at 05:00
  • 1
    @Mlaura Isn't what Matthew Huie shows being the solution of what you need? What else are you asking for? – user3437460 Jan 10 '16 at 09:12

2 Answers2

1

Consider you have

rowOne =2;
rowTwo =3;

Now think without third variable:

if you want to swap them you need to assign one of them to other like:

rowOne=rowTwo;

But if we do so , now rowOne is 3 , but previously it was 2. You need to remember that value and hence we need to store it in temporary memory . That's our third variable. That's how it works.

temp=rowOne ; //This third variable helps to remember the value.
rowOne=rowTwo;
rowTwo=temp;
0

Assuming that int[][] Science has 2 rows and that you would like to swap the order of these two rows, you could do the following in Java:

int tempRow[] = Science[0];
Science[0] = Science[1];
Science[1] = tempRow;

I'm not exactly sure what you meant by rowOne and rowTwo in your question, but you can use a temporary int[] to hold one of the rows, while performing the swap. This works as Java has references to each row in the two-dimensional array.

OneCricketeer
  • 151,199
  • 17
  • 111
  • 216
matthewhuie
  • 186
  • 6