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]);
}
}
}
}
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: