[JAVA] 제어문(control flow statements)

AI 개발자 웅이·2022년 6월 28일
0

Java

목록 보기
3/11

제어문이란 프로그램의 흐름을 제어하는 것이다. 제어문은 크게 조건문과 반복문으로 나눌 수 있다.

조건문

조건문이란 주어진 조건에 따라 다른 수행문이 실행되도록 프로그래밍하는 것이다.

if-else

public static void main(String[] args) {
	int age = 10;
	
    if(age >= 8) {
		System.out.println("학교에 다닙니다.");
    } else {
    	System.out.println("학교에 다니지 않습니다.");
    }
}

switch-case

public static void main(String[] args) {
	int rank = 1;
	char medalColor;

	switch (rank) {
	case 1:
		medalColor = 'G';
		break;
	case 2:
		medalColor = 'S';
		break;
	case 3:
		medalColor = 'B';
		break;
	default:
		medalColor = 'A';
	}
	System.out.println(rank + "등 메달의 색깔은 " + medalColor + "입니다.");
}

반복문

반복문이란 주어진 조건이 만족하는 동안 수행문을 반복적으로 수행하도록 프로그래밍하는 것이다.

for

public static void main(String[] args) {

	// 구구단
    
	int dan;
	int times;
    
	for (dan = 2; dan <= 9; dan++) {
    
		for (times = 1; times <= 9; times++) {
			System.out.println(dan + "X" + times + "=" + dan * times);
		}
		System.out.println();
	}
}

while

public static void main(String[] args) {
	int num = 1;
	int sum = 0;
    
	while (num <= 10) {
		sum += num;
		num++;
	}
	System.out.println("1부터 10까지의 합은 " + sum + "입니다."); // 55
}

do-while

public static void main(String[] args) {

	int num2 = 1;
	int sum2 = 0;

	do {
		sum2 += num2;
		num2++;
	} while (num2 < 1);
	System.out.println(sum2); // 1
}
profile
저는 AI 개발자 '웅'입니다. AI 연구 및 개발 관련 잡다한 내용을 다룹니다 :)

0개의 댓글