본문 바로가기

프로그래밍/알고리즘(자바)

평균구하기 Level 1 : For each문

평균구하기 Level 1


https://programmers.co.kr/learn/challenge_codes/127

public class GetMean {
    public int getMean(int[] array) {
      int sum = 0;
        for(int num : array){              //
            sum += num;
        }
        return sum/array.length;
    }

    public static void main(String[] args) {
        int x[] = {5, 4, 3};
        GetMean getMean = new GetMean();
        // 아래는 테스트로 출력해 보기 위한 코드입니다.
        System.out.println("평균값 : " + getMean.getMean(x));
    }
}


https://wikidocs.net/264 에 for each 구문이 잘 설명되어 있다.


for each 문의 구조는 다음과 같다.

for (type var: iterate) {
    body-of-loop
}

위 iterate는 루프를 돌릴 객체이고 iterate 객체에서 한개씩 순차적으로 var에 대입되어 for문을 수행하게 된다. iterate부분에 들어가는 타입은 루프를 돌릴수 있는 형태인 배열 및 ArrayList등이 가능하다.

단, foreach문은 따로 반복회수를 명시적으로 주는 것이 불가능하고, 1스탭씩 순차적으로 반복될때만 사용가능하다는 제약이 있다.