Ask your own question, for FREE!
Computer Science 8 Online
OpenStudy (ajprincess):

Can someone please help me to write a swap function that swaps two integers using arrays in java?

OpenStudy (espex):

So what is the setup that you're swapping in?

OpenStudy (ajprincess):

sorry didnt get ur ques?

OpenStudy (ajprincess):

@eSpex

OpenStudy (espex):

You are writing a swap method, I was wondering what you had done thus far and how it would fit in the surrounding code.

OpenStudy (espex):

A basic swap is relatively easy. Use a for loop and a temp variable. for(i = 0; i< length - 1; i++) { int tempInt; tempInt = array[i]; array[i] = array[i+1]; array[i+1] = tempInt; }

OpenStudy (ajprincess):

class Swapping { static void swap(int number1, int number2) { int temp=number1; number1=number2; number2=temp; System.out.println("After swapping first integer is = "+number1+" and second integer is = "+number2); } public static void main(String[]args) { int number1 = 2; int number2 = 5; System.out.println("Before swapping first integer is = "+number1+" and second integer is = "+number2); swap(number1,number2); } } This one I wrote for swapping function using variables. Bt I didnt write anything for the above ques

OpenStudy (espex):

Well it looks like you have a handle on the swap, what is it you're having difficulty with?

OpenStudy (ajprincess):

Can you pls explain me the usage of length?

OpenStudy (ajprincess):

I have problem with arrays.

OpenStudy (espex):

In my implementation it is just a variable to indicate that you must stop one less than the length. However you can use length() that will return the length of an unknown array.

OpenStudy (espex):

Say you make a new int array: int [] myArray = new int [10]; You now have a bunch of boxes in memory labeled 0 - 9 0 1 2 3 4 5 6 7 8 9 [] [] [] [] [] [] [] [] [] [] Say I want to store a number in space 5, index number 4, I would say: myArray[4] = 10; Now I have 0 1 2 3 4 5 6 7 8 9 [] [] [] [] [10] [] [] [] [] []

OpenStudy (espex):

So now when I want to swap two numbers, like a bubble sort, I would use my for loop and step through the indexes. for (int i=0; i < 8; i++) { int temp = myArray[i]; myArray[i] = myArray[i+1]; myArray[i+1] = temp; } Now I have moved the value from one end to the other.

OpenStudy (ajprincess):

Will the code look like this then class Swapping { public static void main(String[]args) { int i; for (int i=0; i < 8; i++) { int temp = myArray[i]; myArray[i] = myArray[i+1]; myArray[i+1] = temp; } }

OpenStudy (espex):

You will need to create the array in your declarations, but yes the logic will work. But that will only move the value in position 0 and put in it position 9. Basically it will shift all values to the left by one.

OpenStudy (ajprincess):

class Swapping1 { public static void main(String[]args) { int[] myArray;= new int[5]; for (int i=0; i < 8; i++) { int temp = myArray[i]; myArray[i] = myArray[i+1]; myArray[i+1] = temp; } } } When I compile this I dnt get it right.

OpenStudy (espex):

When you declared your array you made it '5' boxes long, 0 - 4, but your counter in the for loop goes to 8 and will give you an array out of bounds error.

OpenStudy (ajprincess):

ya nw even after changing t to 8 I get errors. Extremely sorry for troubling u a lot.

OpenStudy (espex):

What is your error?

OpenStudy (espex):

http://ideone.com/S5n1Z Here is an example.

OpenStudy (ajprincess):

It says Exception in thread "main" java.lang.ArrayIndexOutOfException:8

OpenStudy (espex):

Yes, you are outside of your array index.

OpenStudy (ajprincess):

when i put 7 the same error is being reported.

OpenStudy (ajprincess):

Ya it comes right for 6

OpenStudy (espex):

Right, if your array declaration is the same you only have 5 indexes. myArray[0], myArray[1], myArray[2],myArray[3],myArray[4].

OpenStudy (espex):

So in this example your counter cannot exceed 4.

OpenStudy (ajprincess):

class Swapping1 { public static void main(String[]args) { int [] myArray=new int[6]; for (int i=0; i < 8; i++) { int temp = myArray[i]; myArray[i] = myArray[i+1]; myArray[i+1] = temp; } } } When I compiled this I got the output correctly.

OpenStudy (espex):

This is the pertinent set of lines: int [] myArray=new int[6]; <---- six spaces created (0 - 5) for (int i=0; i < 8; i++) <----- eight places index (0 - 8) You are three outside your array bounds, four if you count the i+1 in the loop.

OpenStudy (ajprincess):

I didnt give any values for the integers to be swapped. hw do I do that?

OpenStudy (espex):

You can do it in the same manner you would any other variable: myArray[index] = int; So if you wanted to assign 3 to index 5 you would do it like this: myArray[5] = 3; // Recall that index place 5 is the last space of your 6 box array

OpenStudy (ajprincess):

ya I get t. Suppose i<5 then int []myArray=new int[6] Is this right? I am nt getting this part.

OpenStudy (ajprincess):

Sorry for asking it over and over again.

OpenStudy (espex):

That's alright, it is better to ask than to not understand.

OpenStudy (espex):

Let's make up an example. I want to have an array that is 3 spaces long and I wish to store the values of my last three tests in them, 92, 95, 96. So I declare my array of 3 spaces like this: int [] myArray = new int[3]; <-- Note that the 3 means there are 3 places in this array Now arrays are numbered from 0 to <max - 1> so in this case I have 3 spaces and they are numbered from 0 - (3-1) or 0 - 2. To store my three values I would assign them in this manner: myArray[0] = 92; myArray[1] = 95; myArray[2] = 96; Now I have an array that looks like this: [ 92 ][ 95 ][ 96 ] Any questions so far?

OpenStudy (ajprincess):

No upto this I understand.

OpenStudy (ajprincess):

I mean no questions upto this.

OpenStudy (espex):

Okay, so now when I want to access my second score and print it to the screen I just need to: System.out.println(myArray[2]); But if I were to try and print out myArray[3]; I would get garbage because that 'box' does not exist.

OpenStudy (ajprincess):

ya I understand.

OpenStudy (espex):

Alright, do you understand how a for loop works?

OpenStudy (ajprincess):

a little

OpenStudy (espex):

for(i=0;i<3;i++) { System.out.println(myArray[i]); } What this says is, we have an initial condition that is 'i' = 0. Let us check it against the condition in the middle, is it less than 3? Yes it it, so we do the stuff inside. Once inside we see there is an 'i' in myArray[i], so the system replaces that with the value of 'i' at that trip through the loop. So we are in fact saying System.out.println(myArray[0]); on our first run through. Now we have reached the bottom of the loop so we look at the 3rd term of our 'for' which is i++, so we increment i by 1. The process now starts all over again, we check the middle condition, is it less than 3? Yes it is so we do the stuff inside. Again we run across the myArray[i] and again we replace it with the value of i, which on this trip is equal to 1, so we print myArray[1]. Once more at the bottom we check the third term of our for and increment i again. Now 'i' is equal to 2, is it less than 3? Yes, so we go through the process once more. At the bottom we increment i so that it now equals 3, is 3 less than 3? No, so we exit the for loop and move on.

OpenStudy (ajprincess):

ya i understand for loop better now. Thanx a lot:)

OpenStudy (espex):

Np. So take that and see what you can do with your swap program. Just remember that an array can be accessed in the same way as any other variable, you just need to tell it the index you're after, which is why we use the for loop.

OpenStudy (ajprincess):

Can u chck this one. class Swapping1 { public static void main(String[]args) { int [] myArray=new int[4]; myArray[2]=6; for (int i=0; i < 3; i++) { int temp = myArray[i]; myArray[i] = myArray[i+1]; myArray[i+1] = temp; } } } No output displayed.

OpenStudy (ajprincess):

@espex

OpenStudy (espex):

Well the first problem is that you need to assign a value to each of the spaces in the array. When you create an array or variable or any data type the program sets aside memory to hold the value of whatever you define. Problem is, it does not erase the memory and so there could be anything there and when you access that space without initializing it first you will get that garbage and put it into your program.

OpenStudy (ajprincess):

class Swapping1 { public static void main(String[]args) { int [] myArray=new int[4]; myArray[0]=3; myArray[1]=7; myArray[2]=6; for (int i=0; i < 3; i++) { int temp = myArray[i]; myArray[i]= myArray[i+1]; myArray[i+1] = temp; System.out.println("After swapping first integer is = "+myArray[i]+" and second integer is = "+myArray[i+1]); } } } wud t b lyk this

OpenStudy (espex):

You are not using myArray[3] but that is irrelevant as it just sits empty. The rest of it looks fine, it will print out myArray[0] and myArray[1] then myArray[1] and myArray[2].

OpenStudy (espex):

Look at this one: import java.util.*; public class TestProg { public static void main(String[] args) { int[] myArray = new int[4]; int i, temp; for(i=0; i<4; i++) { myArray[i] = i*i; } for(i=0; i<4; i++) { System.out.println(myArray[i]); } for(i=0; i<3; i++) { while(myArray[i] < myArray[i+1]) { temp = myArray[i]; myArray[i] = myArray[i+1]; myArray[i+1] = temp; } } for(i=0; i<4; i++) { System.out.println(myArray[i]); } } }

OpenStudy (ajprincess):

The output displayed for the coding I posted is After swapping first integer is 7 and second integer is 3 After swapping first integer is 6 and second integer is 3 After swapping first integer is 0 and second integer is 3 Is that right?

OpenStudy (espex):

It is. The 0 is in there because you moved the 3, which was first, into the myArray[3] position and that space happen to have a 0 in it.

OpenStudy (espex):

You might want to look at this too: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html It is a pretty good tutorial on arrays.

OpenStudy (espex):

What you are watching in that output is the 3, which was first, bubble its way down the array into the last position.

OpenStudy (ajprincess):

mm ya. I get t nw. So output u get for swapping of integers using arrays will be like the one I got for this prog nt like the one you get for swapping using variables. Isnt t?

OpenStudy (espex):

It would be exactly the same output, just handled differently. The example you just coded could be duplicated by doing this: int i; int x = 3; int y = 7; int z = 6; int temp; temp = x; x = y; y = z; z = temp; System.out.println("After swapping first integer is = "+x+" and second integer is = "+y+" third integer is = "+z+".");

OpenStudy (ajprincess):

I understand it nw. i changed my coding as follws class Swapping1 { public static void main(String[]args) { int [] myArray=new int[3]; myArray[0]=2; myArray[1]=5; for (int i=0; i < 2; i++) { int temp = myArray[i]; myArray[i]= myArray[i+1]; myArray[i+1] = temp; System.out.println("After swapping first integer is = "+myArray[i]+" and second integer is = "+myArray[i+1]); } } } when i compile and run i get the output After swapping first integer is = 5 and second integer is = 2. After swapping first integer is = 0 and second integer is = 2. I want only the first line to be printed nt the second. Hw do I do that?

OpenStudy (espex):

That is because you are only initializing position 0 and 1. Your index runs from 0 - (N-1) with N = (your defined size), in this case, 3. So you need to add a line to initialize myArray[2].

OpenStudy (espex):

Array size Index range 2 0,1 4 0,1,2,3 5 0,1,2,3,4 10 0,1,2,3,4,5,6,7,8,9 1 0

OpenStudy (ajprincess):

Thank you soooooooooooooooooooooo much. :)

OpenStudy (espex):

You're welcome. :)

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!