반복문
- 어떤 작업이 반복적으로 수행되도록 할 때 사용되는 구문
반복문의 종류
- for문: 주로 반복횟수를 알고 있을 때 사용
- 향상된 for문: 컬렉션과 배열을 처리할 때 더 효과적인 문법으로 JDK5.0 이후에 사용 가능
- while문: 조건식으로 반복할 때 주로 사용
- do-while문: 반복하기 전에 먼저 실행해야 하는 구문이 있을 때 사용
for문
for( 초기식; 조건식; 증감식) {
// 명령코딩
}
예제: 1부터 10까지의 합public class ExFor {
public static void main (String[] args)
{
int i , sum = 0;
for ( i=1 ; i<=10 ; i++) {
System.out.printf(i==10?"%d":"%d+",i);
sum+= i;
}
System.out.println("="+sum);
}
}
1+2+3+4+5+6+7+8+9+10=55
향상된 for문
for( 자료형 변수명 : 배열 또는 컬렉션 ) {
// 명령코딩
}
예제: 배열에 담긴 국어 점수 출력public class ExEnhancedFor
{
public static void main (String[] args)
{
int [] kors = new int[5];
kors[0] = 100;
kors[1] = 90;
kors[2] = 77;
kors[3] = 23;
kors[4] = 88;
for (int kor : kors) {
System.out.println(kor);
}
}
}
100
90
77
23
88
while문
while( 조건식 ) {
// 조건식이 참일 동안 반복될 명령 코딩
}
예제: 10부터 0까지의 합public class ExWhile
{
public static void main (String[] args)
{
int i = 10 , sum = 0;
while( i >= 0 ){
System.out.printf(i==0?"%d":"%d+",i);
sum += i;
i--;
}
System.out.println("="+sum);
}
}
10+9+8+7+6+5+4+3+2+1+0=55
do-while문
do{
// 먼저 한번 실행하고, 조건식이 참일 동안 반복할 명령 코딩
}while( 조건식 );
예제: 증가치에 따라 증가하는 항 값의 누적 합public class ExDoWhile
{
public static void main (String[] args) throws java.lang.Exception
{
int h = 1; // n 항의 누적 합
int n = 1; // 각 항: [1]+[2]+[4]+[7]+[11]+[16]+[22]
int k = 0; // 증가치: 1 2 3 4 5 6
do{
k+=1;
n += k;
if( n > 100) break;
h += n; // (누적)
System.out.printf("%d - %d - %d\n",n,k,h);
}while(true);
}
}
2 - 1 - 3
4 - 2 - 7
7 - 3 - 14
11 - 4 - 25
16 - 5 - 41
22 - 6 - 63
29 - 7 - 92
37 - 8 - 129
46 - 9 - 175
56 - 10 - 231
67 - 11 - 298
79 - 12 - 377
92 - 13 - 469