dev/Java
[Java]반복문 - for, while, do~while
mingracle
2022. 1. 5. 02:22
for문
: 반복횟수 정해져있는경우. 배열과 함께 주로사용
for(초기식; 조건식; 증감식){ 수행문; } |
수행순서 - 초기식 → 조건식:false = for문 종료 - 초기식 → 조건식:true → 수행문 → 증감식 → 조건식:true → 수행문 → 증감식 (조건식 true면 false까지 반복) |
※초기식을 외부에서 선언했을 때 생략가능
for(; i<=5; i++)
※for문에서 int i를 선언했으면 외부에서 i를 불러오지 못한다.(지역변수)
for(i=1; i<=5; i++)
//숫자를 입력하면 그 숫자에 맞는 구구단을 출력하세요
public class ForEx3 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("단 : ");
int dan = s.nextInt();
int result;
for(int i = 1; i<=9; i++) {
result = dan * i;
System.out.printf("%d * %d = %d\r", dan, i, result);
}
}
}
더보기
더보기
실행결과
단 : 5
5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
//for문을 이용해 알파벳 대문자 A~Z까지 출력
public class ForEx5 {
public static void main(String[] args) {
char alpabet = 'A'; //65
//char타입은 인코딩 처리해서 숫자를 저장하고 있음
for(; alpabet <= 'Z'; alpabet++)
System.out.println(alpabet);
}
}
+ break : 가장가까운 반복문(for, while문) 종료 |
+ continue : 반복문과 함께 쓰이며, 반복 수행하지 않고 조건식 및 증감식 수행 |
for(int i=1 ; i<=10 ; i++) { if(i%2 == 0) { break; } System.out.print (i); } //break는 반복문(for문)을 완전히 빠져나옴 //결과: 1 |
for(int i=1 ; i<=10 ; i++) { if(i%2 == 0) { continue; } System.out.print(i); } //continue를 만나면 증감식 수행 // 결과: 1 3 5 7 9 |
while문
: 특정 조건이 주어졌을 때 조건 만족할 때까지 반복
while(조건식){ 수행문; } |
수행순서 : 조건식 true = 반복 조건식:true → 수행문 → 조건식:true → 수행문 .. (반복) → 조건문:false = while문 종료 |
public class WhileEx3 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
boolean stop = false;
while(!stop) {
System.out.print("번호를 입력하세요 : ");
int num = s.nextInt();
if(num == 1) {
System.out.println("1을 입력했습니다.");
}else if(num == 2) {
System.out.println("2를 입력했습니다.");
}else if(num == 3) {
System.out.println("3을 입력했습니다."); //프로그램이 종료되지 않고 반복
}else {
System.out.println("잘못된 번호를 입력했습니다.");
stop = true; // while문이 false가 되면서 종료
}
}
System.out.println("프로그램 종료");
}
}
더보기
더보기
실행결과
번호를 입력하세요 : 2
2를 입력했습니다.
번호를 입력하세요 : 1
1을 입력했습니다.
번호를 입력하세요 : 3
3을 입력했습니다.
번호를 입력하세요 : 4
잘못된 번호를 입력했습니다.
프로그램 종료
//1~50까지의 숫자 중 4의 배수만 더하기
public class WhileEx4 {
public static void main(String[] args) {
int i = 1;
int sum = 0;
while(i<=50) {
if(i%4==0) {
sum += i;
}
i++;
}
System.out.println("1부터 50까지 4의배수 합은 "+ sum +"입니다.");
}
}
do~while문
: 수행문이 반드시 한 번 이상 수행되어야 하는 경우 사용
do{ 수행문; }while(조건식); |
수행순서 : 조건식이 true = do로 돌아가 반복 |
public class DoWhileEx1 {
public static void main(String[] args) {
int i = 10;
do {
System.out.println("실행");
}while(i<5);
}
}