-6

I am new here and new to programming. I have an assignment which consists of reversing the elements of an array, but the array reverse method cannot be used. I do not know how I can achieve this. I tried using a for loop but it did not work. Thanks in advance.

trying to reverse something like this: 1,4,9,16,9,7,4,9,11 into 11,9,4,7,9,16,9,4,1

DevWolf
  • 1
  • 1

2 Answers2

2

So since this is a homework question I am going to not provide you the full answer but instead give you some hints.

If you are allowed to make an additional array try the following: Create a new array that will contain the elements in reverse. iterate through your initial array starting from the end and moving to element 0. As you do so just set initialArray[i] = newArray[index] Note that i and index are just variables that I made up. Part of the difficulty of this assignment is figuring out how to do the assignment between the two arrays so I will leave that to you!

Feel free to ask any more questions and I can try to guide you to the solution.

Good Luck!

Jay
  • 157
  • 2
  • 11
1

Use a for loop and a second array would be the simplest way.

int[] array = new int[]{ 1, 4, 9, 16, 9, 7, 4, 9, 11 };
int[] array2 = array;
int count = 0;
for(int i = array.length-1; i >= 0; i--) {
    array2[count] = array[i];
    count++;
}

A more complex solution using only one array would be temporarily save the value to an outside int and swap them.

int count = 0;
int[] array = new int[]{ 1, 4, 9, 16, 9, 7, 4, 9, 11 };
for(int i = array.length-1; i >= count; i--) {
    int x = array[i];
    array[i] = array[count];
    array[count] = x;
    count++;
}
Dave K.
  • 258
  • 1
  • 10