-2

Could someone please thoroughly explain why this prints 21003 versus 32103? I'm really confused by this. Thank you!

public class question1{

  public static void reduce (int[] arr, int len)
  {
    for (int k=0; k<len; k++)
    {
        arr[k]--;
    }
    len--;    
  }

  public static void main (String args []){

    int [] counts = {3,2,1,0};
    int len = 3;
    reduce(counts, len);

    for(int c: counts)
    {
        System.out.print(c+" ");
    }
    System.out. println(len);    
  } 
}
Thodgnir
  • 148
  • 1
  • 11

1 Answers1

1

The reduce method is decrementing the first 3 values in the counts array dues to the len variable in the for loop. So thats why the first 3 numbers are being outputted as 210 instead of 321.

NiallMitch14
  • 1,198
  • 1
  • 12
  • 28
  • Just to confirm, len -- doesn't change the update step in the for loop each time, correct? Also, I thought printing counts without referencing the method would print the original array. Could someone please explain this? Thank you. – Teresa Hoffman Feb 25 '16 at 03:54