메뉴 건너뛰기

Java 기초 - while, for

Eugene 2018.04.05 01:33 조회 수 : 860

while문의 사용은 다음과 같다.

 

초기화

while (루프 반복 조건) {

    실행문;

    증분;

}

 

for문의 사용은 다음과 같다.

 

for (초기화; 루프 반복 조건; 증분) {

}

 

예를 들어 1부터 10까지 더하는 while 루프를 만들어보자.

int total = 0;

int count = 1;

 

while (count <= 10) {

    total = total + count; // total += count;

    count++; // count = count + 1과 동일

}

 

위 예를 for루프로 만든다면,

 

int total = 0;

 

for (int count = 1; count <= 10; count++) {

    total += count;

}

가 될 것이다.

 

물론, 두 루프의 total은 55가 될 것이다.

 

위 for루프에서 int count = 1;의 초기화를 for루프 밖에서의 처리도 가능하다.

int total = 0;

int count = 1;

 

for (; count <= 10; count++) {

    total += count;

}

 

물론 결과는 같다.