-2

The program is meant to invert the values in the array. When the program is run, the only values that show are 3 and 2, then it ends. I've been looking online but I can't figure out why this happens. Switching val[i] for temp in the SOP gives values of 0 and 1 then ends.

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

            System.out.println(val[i]);
        }
Richard Chambers
  • 16,643
  • 4
  • 81
  • 106
Marco Aiello
  • 179
  • 10

3 Answers3

3

Because your for loop only iterate for values 0 and 1, then at the end it prints only 0th and 1st elements, try following

    int[] val = {0, 1, 2, 3};
    int temp;            
    for(int i=0;i<val.length/2;i++) {
                temp=val[i];
                val[i]=val[val.length - 1 - i];
                val[val.length - 1 - i]=temp;
    }
    for(int i=0;i<val.length;i++){
        System.out.println(val[i]);
    }
Chamila Wijayarathna
  • 1,815
  • 5
  • 30
  • 54
1

It makes sense to use val.lenth/2 to only traverse half of the array, swapping values as you go. It does not make sense to only traverse half of the array while trying to print the entire array. Try using another for loop to print out the contents of the ENTIRE array.

edit: I tried not to just give the answer

dkh
  • 23
  • 5
1
for(int i=0;i<val.length/2;i++)

val.length/2= 4/2 = 2 so that the for loop will only run twice. Thats why it prints only the 3 and 2.

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

            System.out.println(val[i]);

        }