글을 시작하며
간혹 같은 스크립트나 같은 출력 명령어를 여러번 반복시켜야할 때가 종종 있다. 하지만 그렇다고 모든 반복사항을 모두 쓸 수는 없는 노릇이다. 그래서 있는게 반복문, 즉 for 문이다.
용도
같은 명령어들을 여러번 작동시킴.
같은 명령어들을 여러번 작동시킴.
문법
for([정수형 변수 유형] [정수형 변수 이름] = [초기화 값]; [정수형 변수 이름] [비교 연산자] [비교할 값]; 증가 공식){
[명령어]
}
예제
[명령어]
}
예제
public class EX{
public static void main(String[]args){
for (int i = 0; i == 10; i++){
System.out.println("Hello World!");
System.out.println("Counted: " + i);
}
for (int i = 0; i == 10; i++){
System.out.println("Hello World!");
System.out.println("Counted: " + i);
}
}
}
출력 결과:
Hello World!
Counted: 0
Hello World!
Counted: 1
Hello World!
Counted: 2
Hello World!
Counted: 3
Hello World!
Counted: 4
Hello World!
Counted: 5
Hello World!
Counted: 6
Hello World!
Counted: 7
Hello World!
Counted: 8
Hello World!
Counted: 9
Hello World!
Counted: 10
설명
위의 예제는 Hello World! 와 Counted: [카운트수] 를 출력하는 예제이다. 여기서 변수 i 는 카운터 변수이다. for 문이 한번 작동할때마다 i++ 부분에서 변수 i 가 계속 1 씩 증가하므로써, i==10 이라는 조건에 충족을 하면 작동을 그만한다.
이 외에도 break; 라는 코드로 for 문의 조건을 충족하지 않았음에도 for 문을 빠져나올 수 있다.
이 외에도 break; 라는 코드로 for 문의 조건을 충족하지 않았음에도 for 문을 빠져나올 수 있다.