For questions 13 - 15, assume an int array, candy, stores the number of candy bars sold by a group of children where candy[j] is the number of candy bars sold by child j. Assume there are 12 children in all. 15) What does the following method do? ``` public int question15( ) { int value1 = 0; int value2 = 0; for(int j=0; j<12; j++) if(candy[j] > value1) { value1 = candy[j]; value2 = j; } return value2; } ``` a) It returns the total number of candy bars sold b) It returns the total number of children who sold 0 candy bars c) It returns the total number of children who sold more than 0 candy bars d) It returns the number of candy bars sold by the child who sold the most candy bars **e) It returns the index of the child who sold the most candy bars**(정답) 질문입니다. 처음 만나게 되는 "if(candy[j] > value1)"에서 candy[j]의 초기값이 없어보이는데, if문이 제대로 동작하는 지요? 그리고 return값이 value2(child)인데 정답에서는 return값이 numbers of candy(사탕개수)라고 하니 더욱이 이해가 안갑니다. 설명 부탁드려요. 감사합니다.
# 배열의 초기 값과 인덱스 1) 처음 만나게 되는 “if(candy[j] > value1)”에서 candy[j]의 초기값이 없어보이는데, if문이 제대로 동작하는 지요? 배열은 초기값을 대입하지 않으면 기본 값이 설정 됩니다. candy 배열은 int 타입이므로 candy[j]의 초기값은 0이 저장될 것입니다. ``` int[] arr1 = new int[3]; // [0, 0, 0] double[] arr2 = new double[3]; // [0.0, 0.0, 0.0] booelan[] arr3 = new boolean[3]; // [false, false, false] String[] arr4 = new String[4]; // [null, null, null] ``` 2) return값이 value2(child)인데 정답에서는 return값이 numbers of candy(사탕개수)라고 하니 더욱이 이해가 안갑니다. question15() 메소드는 배열 중 가장 큰 값을 가진 요소의 위치 즉 인덱스를 반환합니다. 따라서 정답은 **e) It returns the index of the child who sold the most candy bars(정답)** 가 맞습니다. ``` public int question15( ) { int value1 = 0; int value2 = 0; for(int j=0; j<12; j++) if(candy[j] > value1) { value1 = candy[j]; value2 = j; } return value2; } ``` 위코드는 배열에서 가장 큰 값의 값을 찾아 value1에 대입합니다. 그리고 value2에는 해당 값을 가진 배열의 위치 즉, 인덱스 값을 대입하는데요, 최종적으로 question15() 메소드의 반환값은 배열의 인덱스 값인 value2를 반환하고 있습니다.
이해가 잘 되네요. 감사합니다~