0

So let's say I have an array called

char[] arr = new char[8];

and using a for loop i assign it all 0

for (int i = 0; i<8;i++)
{
     arr[i]='0';
}

and i have another array and lets say i have an array with

char[] reverseArr = {'A','B','C','D','E','F','G','Z'};

how do you assign it with reverse order of reverseArr to arr? So i would have an array called arr with an element of Z G F E D C B A.

Thanks in advance.

cohsta
  • 187
  • 1
  • 4
  • 14

1 Answers1

1

You can have two variables on for statement and assign the last value of array to the first position on reverse array.

char[] reverseArr = {'A','B','C','D','E','F','G','Z'};
char[] arr = getReverseArray(reverseArr);

public char[] getReverseArray(char[] arrayToReverse) {
   char[] reverseArray = new char[arrayToReverse.length];
   for(int i = arrayToReverse.length - 1, j = 0; i >= 0; i--, j++) {
       reverseArray[j] = arrayToReverse[i];
   }
   return reverseArray;
}

By the way, you don't need to assign values to the char array to replace it. (You're assigning '0' to each array position);

Raphael Amoedo
  • 4,233
  • 4
  • 28
  • 37