반복문
1. 반복문 - for
- 주어진 횟수만큼 반복하여 실행하는 구조
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
for (초기치;조건문;증가치;) {
반복하여 실행할 내용;
}
// ex)
int[] arr = {1,2,3,4,5};
for (int i = 0 ; i < 5 ; i++) {
System.out.println(arr[i]);
}
// (추가) forEach
int[] arr = {1,2,3,4,5};
for (int ele : arr) {
System.out.println(ele);
}
2. 반복문 - while
- 조건문이 만족하는 동안 반복하여 실행하는 구조
- while과 do-while 구조가 있음
1
2
3
4
5
6
7
8
9
10
11
12
13
14
while (조건문) {
반복하여 실행할 내용;
}
do {
반복하여 실행할 내용;
} while (조건문);
// ex) 아래는 knock을 한번 출력하고, while의 knock조건에 의해 루프를 탈출
boolean knock = false;
do {
System.out.println("knock");
} while (knock);
This post is licensed under CC BY 4.0 by the author.