[JAVA] 반복문 (For문)
제어문이란?
- 프로그램의 흐름을 제어하는 문법
1) 조건문 : 정해진 조건에 따라 흐름을 제어하는문법 | |
2) 반복문 :정해진 조건에 따라 흐름을 반복하는 문법 |
반복문이란?
- 특정 작업을 반복적으로 수행하고 싶을 때 사용하는 문법
- 반복되는 명령을 간편하게 처리하기 위해 사용
반복문의 종류 3가지
1) for
2) while
3) do - while
-for문
변수가 처음엔 ~부터 ~가 될 때까지 반복할게 (특정한 횟수동안 작업을 반복하고 싶을 때 사용) |
for ( 초기식;조건식;증감식) { 초기식에 선언된 변수가 조건식이 참일 동안에 반복할 명령; } |
- 초기식 : 변수를 생성
- 조건식 : 변수의 마지노선 설정
- 증감식 : 변수의 변화량 설정
for문의 실행 순서:
초기식 → 비교식 → 명령 → 증감식 이때, 초기식은 반복문이 실행될 때 한번만 실행된다 |
ex) 반목문을 사용하지 않았을 때
" A야 1번부터 10번까지 컴퓨터 화면 좀 켜줘 "라는 말을
반목문을 사용하지 않고 10번 출력하기 위해 우리는
System.out.println("A야 1번 컴퓨터 화면 좀 켜줘");
System.out.println("A야 2번 컴퓨터 화면 좀 켜줘");
System.out.println("A야 3번 컴퓨터 화면 좀 켜줘");
System.out.println("A야 4번 컴퓨터 화면 좀 켜줘");
System.out.println("A야 5번 컴퓨터 화면 좀 켜줘");
System.out.println("A야 6번 컴퓨터 화면 좀 켜줘");
System.out.println("A야 7번 컴퓨터 화면 좀 켜줘");
System.out.println("A야 8번 컴퓨터 화면 좀 켜줘");
System.out.println("A야 9번 컴퓨터 화면 좀 켜줘");
System.out.println("A야 10번 컴퓨터 화면 좀 켜줘"); 이 말을 1번부터 10번까지 반복해서 입력해야 한다
ex) 반목문을 사용하였을 때
package practice;
public class pra5 {
public static void main(String[] args) {
for (int i=1;i<=10;i++) {
System.out.println("A야 "+i+"번 컴퓨터 화면 좀 켜줘");
}
}
}
만약에 i가 10보다 같거나 클 때까지 1씩 증가해
라는 조건을 반복 for문을 사용하여 쉽고 간결하게 출력하였다
ex) 만약에 i가 1보다 작거나 같을 때까지 1씩 감소해
package practice;
public class pra5 {
public static void main(String[] args) {
for (int i=10;i>=1;i--) {
System.out.println("A야 "+i+"번 컴퓨터 화면 좀 켜줘");
}
}
}
ex) 만약에 i가 10보다 작거나 클 때까지 2씩 증가해
package practice;
public class pra5 {
public static void main(String[] args) {
for (int i=1;i<=10;i+=2) {
System.out.println("A야 "+i+"번 컴퓨터 화면 좀 켜줘");
}
}
}
ex)
package practice;
public class pra5 {
public static void main(String[] args) {
int sum=0;
for (int i=1;i<=10;i++) {
System.out.printf("i=%d,sum=%d\n",i,sum+=i);
}
}
}