Having trouble with the output of my reversal array

60 views Asked by At

Ok so I have my code and everything works great but I'm not seeing why my output gives me two reversals instead of the one. The last one is correct but the first output for the reversal is a little mixed up.

public class ICE17 {

       static //Examine the following program:
       class ArrayProblems {

            public static void main(String[] args) {

                int[] val = { 0, 1, 2, 3 };
                int sum = 0; //write code here

                for (int i = 0; i < val.length; i++) {
                    sum += val[i];
                 }

                System.out.println("Sum of all numbers = " + sum);
                reverse();
            }
            public static void reverse() {
                int[] val = { 0, 1, 2, 3 };
                //int temp=0;
                System.out.println("Original Array: " + val[0] + " " + val[1] + " " + val[2] + " " + val[3]);
                // write code here to reverse the order of the numbers in the array
                for (int i = 0; i < val.length / 2; i++) {

                    int temp = val[i];
                    val[i] = val[val.length - 1 - i];
                    val[val.length - 1 - i] = temp;    
                    System.out.println("Reversed Array: " + val[0] + " " + val[1] + " " + val[2] + " " + val[3]);

                }
            }
        }
    }
2

There are 2 answers

0
hsingh On

Erick has answered right for fixing the print issue. You are printing the array within for loop, so it will print it for length/2 times.

Other thing that your reverse method is creating a local array and reversing it. If you really want to reverse the array created in main method then write a function which will take an array as input like below:

public class ICE17 {

    public static void reverseArray(int[] val) {
        for (int i = 0; i < val.length / 2; i++) {
            int temp = val[i];
            val[i] = val[val.length - 1 - i];
            val[val.length - 1 - i] = temp;
        }
    }

    public static void printArray(int[] val) {
        for(int i: val) {
            System.out.print(i + " ");
        }
        System.out.println();
    }
    public static void main(String[] args) {
        int arr[] = { 0, 1, 2, 3 };
        System.out.println("Array before reverse");
        printArray(arr);
        reverseArray(arr);
        System.out.println("Array after reverse");
        printArray(arr);
    }
}
1
Erick Sauceda On

Check your curly brackets!

for (int i = 0; i < val.length / 2; i++) {
    int temp = val[i];
    val[i] = val[val.length - 1 - i];
    val[val.length - 1 - i] = temp;

    System.out.println("Reversed Array: " + val[0] + " " + val[1] + " " + val[2] + " " + val[3]);
}

As you can see, you are printing out the reversed array each time the for loop runs.
The reversal isn't finished in the first loop, so it prints out a little funny.