In: Computer Science
JAVA CODE
Give the definition of a static method called showArray that has an array of base type char as a single parameter and that writes to the screen each character in the array on a separate line. It then writes the same array characters in reverse order. This method returns a character array that holds these two lines of characters in the order that you printed them.
CODE:
public class Array {
public static char[] showArray(char[] array) {
// creating a char array twice the capacity to store the contents of
// array in forward and reverse
char[] combined = new char[array.length * 2];
int index = 0;
// looping from first character to the last
for (int i = 0; i < array.length; i++) {
// printing current character on a separate line
System.out.println(array[i]);
// adding current character to combined array at index 'index'
combined[index] = array[i];
// updating index
index++;
}
// looping from last character to the first
for (int i = array.length - 1; i >= 0; i--) {
// printing current character on a separate line
System.out.println(array[i]);
// adding current character to combined array at index 'index'
combined[index] = array[i];
// updating index
index++;
}
// returning combined array
return combined;
}
public static void main(String[] args) {
char initialArray[] =
{'a','c','d','e'};
// Now arr will
contain required format of array;
char arr[] =
showArray(initialArray);
}
}