조건문과 제어 구조
프로그램 실행 중, 명령문들의 순서는 프로그램의 결과에 직접적인 영향을 미칩니다. 따라서 각 문장이 어떻게 실행되는지 이해하고 이를 제어하는 방법을 알아야 합니다.
1. 기본 제어 구조
- 순차 구조: 가장 간단한 형태로, 코드가 작성된 순서대로 차례로 실행됩니다.
- 분기 구조: 특정 조건에 따라 다른 코드 블록을 실행합니다 (if, switch).
- 반복 구조: 조건이 만족될 때까지 같은 코드를 반복해서 실행합니다 (for, while, do...while).
조건문: if 문
1. 단일 if 문
if (조건식) {
// 조건이 참인 경우 실행할 코드
}
실행 흐름:
- 조건식의 값을 계산합니다.
- 값이 true라면 해당 코드 블록을 실행합니다.
- false라면 다음 코드로 넘어갑니다.
예제: 숫자 비교
public class IfExample {
public static void main(String[] args) {
int num1 = 50;
int num2 = 50;
if (num1 == num2) {
System.out.println("두 수는 같습니다.");
}
}
}
2. if-else 문
if (조건식) {
// 참일 때 실행할 코드
} else {
// 거짓일 때 실행할 코드
}
예제: 금액에 따른 선택
import java.util.Scanner;
public class MoneyChoice {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("현재 소지금을 입력하세요: ");
int money = scanner.nextInt();
if (money >= 100) {
System.out.println("럭셔리 식당으로!");
} else {
System.out.println("간단한 분식점으로!");
}
}
}
3. 다중 if-else 문
if (조건1) {
// 실행코드1
} else if (조건2) {
// 실행코드2
} else {
// 나머지 경우 실행
}
예제: 성적에 따른 상품 지급
import java.util.Scanner;
public class GradeReward {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("성적을 입력하세요: ");
int score = scanner.nextInt();
if (score >= 95 && score <= 100) {
System.out.println("자전거 한 대를 드립니다!");
} else if (score >= 90 && score < 95) {
System.out.println("놀이공원 하루 무료 입장권!");
} else if (score >= 80 && score < 90) {
System.out.println("트랜스포머 장난감을 드립니다!");
} else {
System.out.println("아무것도 없습니다...");
}
}
}
switch 문
switch (변수) {
case 값1:
// 실행코드1
break;
case 값2:
// 실행코드2
break;
default:
// 기본 실행코드
break;
}
예제: 요일별 운동 계획
import java.util.Scanner;
public class WorkoutPlan {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("요일 번호를 입력하세요 (1-7): ");
int day = scanner.nextInt();
switch (day) {
case 1:
System.out.println("오늘은 달리기!");
break;
case 2:
System.out.println("수영 시간입니다.");
break;
case 3:
System.out.println("산책하기!");
break;
case 4:
System.out.println("자전거 타기!");
break;
case 5:
System.out.println("복싱 트레이닝!");
break;
case 6:
System.out.println("등산 가자!");
break;
case 7:
System.out.println("휴식! 맛있는 음식 먹기");
break;
default:
System.out.println("잘못된 입력입니다.");
break;
}
}
}
반복문: for, while, do...while
1. for 반복문
for (초기화; 조건식; 증감식) {
// 실행코드
}
예제: 합계 계산
public class SumCalculator {
public static void main(String[] args) {
int total = 0;
for (int i = 1; i <= 10; i++) {
total += i;
}
System.out.println("1부터 10까지의 합은 " + total + "입니다.");
}
}
2. while 반복문
while (조건식) {
// 실행코드
}
예제: 피보나치 수열 생성
public class FibonacciSeries {
public static void main(String[] args) {
int first = 0, second = 1;
int count = 10;
System.out.print("피보나치 수열: ");
int i = 0;
while (i < count) {
System.out.print(first + " ");
int next = first + second;
first = second;
second = next;
i++;
}
}
}
3. do...while 반복문
do {
// 실행코드
} while (조건식);
예제: 최소 한 번 이상 실행
import java.util.Scanner;
public class DoWhileExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number;
do {
System.out.print("양수를 입력하세요: ");
number = scanner.nextInt();
} while (number <= 0);
System.out.println("입력된 양수는 " + number + "입니다.");
}
}