Here's my code: Spoiler: code PHP: import java.util.Scanner;public class ModifyArray { public static void swapArrayEnds(int[] sortArray, int numElem) { int temp = 0; if (numElem > 0) { temp = sortArray[0]; sortArray[0] = sortArray[numElem]; sortArray[numElem] = temp; } return; } public static void main (String [] args) { int numElem = 4; int[] sortArray = new int[numElem]; int i = 0; sortArray[0] = 10; sortArray[1] = 20; sortArray[2] = 30; sortArray[3] = 40; swapArrayEnds(sortArray, numElem); for (i = 0; i < numElem; ++i) { System.out.print(sortArray[i]); System.out.print(" "); } System.out.println(""); return; }} My problem is that my method "swapArrayEnds" does not swap the ends and gives me the "Program end never reached. This is commonly due to an invalid memory/array access or divide by 0" text. How do I fix it? Edit: Nevermind. I see where I went wrong. Orz. I had to subtract 1 from numElem.
as a short tip you can do sortArray.length in the sub to get the number of elements in the array without have to pass it manually
You should pass (the length of the array-1) to the swapArrayEnds function. sortArray is stored starting from 0 to 3 in this case and the function tries to access the 4th element, which should not exist.
Actually, don't even pass the length of the array because it is redundant. Instead of: public static void swapArrayEnds(int[] sortArray, int numElem) or public static void swapArrayEnds(int[] sortArray, int sortArray.length) Simply use: public static void swapArrayEnds(int[] sortArray) Then in the body of the function: if (sortArray.length > 0) ============ You want to do this because it's less code you need to write and one less variable you need to set (numElem is no longer a variable you need). If you ever need to make changes to your code, it's one less potential thing that can go wrong.