Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program to reverse the contents of a character array. -- Use the followi

ID: 3653361 • Letter: W

Question

Write a program to reverse the contents of a character array.

-- Use the following method signature:

public static char[ ] reverseArray(char[ ] anArray)

-Only have one return statement as the last statement of this method.

-Print the original array right after it is initialized and again after you have called your reverse method and printed its result.

- Use the following char array to test your method:

-- char[] letters = {'s', 't', 'r', 'e', 's', 's', 'e', 'd'};

The output should look like:

stressed

desserts

stressed

Explanation / Answer

public class ReverseArray{
        // main function
        public static void main(String []args){
                char[] letters = {'s', 't', 'r', 'e', 's', 's', 'e', 'd'};
                // call printArray
                printArray(letters);
                //call reverseArray
                letters = reverseArray(letters);
                // print changed output
                printArray(letters);
        }
        //reverseArray function
        public static char[ ] reverseArray(char[ ] anArray){
                int len = anArray.length;
                int i;
                // loop for (length of string )/ 2 times . and change ith element with len - i - 1 .
                // keep in mind if we run the loop for len time we will reverse the array two times which is same as original
                for( i = 0 ; i <= len/2; i++) {
                        char temp = anArray[i] ;
                        anArray[i] = anArray[len -i - 1] ;
                        anArray[len -i - 1] = temp;
                }
                return anArray;
        }
        public static void printArray(char A[]){
                int i;
                for ( i = 0 ;i < A.length;i++)
                        System.out.print(A[i]+",");
                System.out.println();
        }
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote