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?
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?
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;
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.