Topic 2: while문과 do-while문 🔄
🎯 학습 목표
- while문의 구조와 동작 원리를 이해할 수 있다
- do-while문의 특징과 사용 시점을 파악할 수 있다
- for문과 while문의 차이점을 설명할 수 있다
🔄 while문
조건이 참인 동안 계속해서 반복 실행하는 반복문입니다.
기본 구조
while (조건) {
// 조건이 참일 때 반복 실행할 코드
}
기본 예제
#include <iostream>
using namespace std;
int main() {
int count = 1;
cout << "1부터 5까지 출력:" << endl;
while (count <= 5) {
cout << count << " ";
count++; // 조건 변경 (중요!)
}
cout << endl;
return 0;
}
사용자 입력을 받는 while문
#include <iostream>
using namespace std;
int main() {
int number;
cout << "0을 입력하면 종료됩니다." << endl;
while (true) { // 무한 루프
cout << "숫자를 입력하세요: ";
cin >> number;
if (number == 0) {
cout << "프로그램을 종료합니다." << endl;
break; // 루프 탈출
}
cout << "입력한 숫자: " << number << endl;
}
return 0;
}
🔄 do-while문
최소 1번은 실행되는 것이 보장되는 반복문입니다.
기본 구조
do {
// 최소 1번은 실행되는 코드
} while (조건);
while문과 do-while문 비교
#include <iostream>
using namespace std;
int main() {
// 1. while문 (조건이 처음부터 거짓)
int count1 = 10;
cout << "while문 결과: ";
while (count1 < 5) {
cout << count1 << " ";
count1++;
}
cout << "(아무것도 출력되지 않음)" << endl;
// 2. do-while문 (조건이 처음부터 거짓)
int count2 = 10;
cout << "do-while문 결과: ";
do {
cout << count2 << " ";
count2++;
} while (count2 < 5);
cout << "(10이 출력됨)" << endl;
return 0;
}
do-while문 활용 예제 - 간단한 메뉴
#include <iostream>
using namespace std;
int main() {
int choice;
do {
// 메뉴 출력
cout << "\n=== 메뉴 ===" << endl;
cout << "1. 안녕하세요" << endl;
cout << "2. 좋은 하루" << endl;
cout << "0. 종료" << endl;
cout << "선택: ";
cin >> choice;
if (choice == 1) {
cout << "안녕하세요! 반갑습니다." << endl;
} else if (choice == 2) {
cout << "좋은 하루 보내세요!" << endl;
} else if (choice == 0) {
cout << "프로그램을 종료합니다." << endl;
} else {
cout << "잘못된 선택입니다. 다시 선택해주세요." << endl;
}
} while (choice != 0); // 0을 입력할 때까지 반복
return 0;
}
🆚 for vs while 비교
언제 무엇을 사용할까?
for문을 사용하기 좋은 경우:
- ✅ 반복 횟수가 명확할 때
- ✅ 인덱스를 사용한 반복
- ✅ 배열이나 컨테이너 순회
// 배열 출력 - for문이 적합
int arr[5] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; i++) {
cout << arr[i] << " ";
}
while문을 사용하기 좋은 경우:
- ✅ 반복 조건이 복잡할 때
- ✅ 반복 횟수가 불명확할 때
- ✅ 사용자 입력에 따른 반복
// 사용자 입력 처리 - while문이 적합
int input = 1;
while (input != 0) {
cout << "숫자 입력 (0으로 종료): ";
cin >> input;
if (input != 0) {
cout << "입력한 숫자: " << input << endl;
}
}
🎮 간단한 예제 - 카운터 프로그램
#include <iostream>
using namespace std;
int main() {
int count = 0;
int input;
cout << "=== 간단 카운터 ===" << endl;
cout << "숫자를 입력하면 카운터가 증가합니다 (0 입력시 종료)" << endl;
while (input != 0) {
cout << "\n현재 카운트: " << count << endl;
cout << "숫자 입력 (0으로 종료): ";
cin >> input;
if (input != 0) {
count++;
cout << "카운트가 증가했습니다!" << endl;
}
}
cout << "최종 카운트: " << count << endl;
cout << "프로그램을 종료합니다." << endl;
return 0;
}
⚠️ 주의사항
1. 무한 루프 방지
// 위험한 코드 - 무한 루프!
int count = 1;
while (count <= 10) {
cout << count << endl;
// count++; 이 없으면 무한 루프!
}
// 안전한 코드
int count = 1;
while (count <= 10) {
cout << count << endl;
count++; // 반드시 조건을 변경해야 함!
}
2. 올바른 조건 설정
// 잘못된 조건
int i = 0;
while (i < 10); { // 세미콜론 때문에 무한 루프!
cout << i << endl;
i++;
}
// 올바른 조건
int i = 0;
while (i < 10) { // 세미콜론 제거
cout << i << endl;
i++;
}
💡 실습 문제
🔥 도전 문제 1: 입력 검증 시스템
#include <iostream>
using namespace std;
int main() {
int number;
bool validInput = false;
cout << "1부터 100 사이의 숫자를 입력하세요." << endl;
while (!validInput) {
cout << "숫자 입력: ";
cin >> number;
if (number >= 1 && number <= 100) {
validInput = true;
cout << "✅ 올바른 입력입니다: " << number << endl;
} else {
cout << "❌ 1부터 100 사이의 숫자를 입력해주세요!" << endl;
}
}
return 0;
}
🔥 도전 문제 2: 간단한 계산기
#include <iostream>
using namespace std;
int main() {
int num1, num2;
int choice;
cout << "=== 간단 계산기 ===" << endl;
do {
cout << "\n1. 덧셈" << endl;
cout << "2. 뺄셈" << endl;
cout << "0. 종료" << endl;
cout << "선택: ";
cin >> choice;
if (choice == 1) {
cout << "첫 번째 숫자: ";
cin >> num1;
cout << "두 번째 숫자: ";
cin >> num2;
cout << num1 << " + " << num2 << " = " << (num1 + num2) << endl;
} else if (choice == 2) {
cout << "첫 번째 숫자: ";
cin >> num1;
cout << "두 번째 숫자: ";
cin >> num2;
cout << num1 << " - " << num2 << " = " << (num1 - num2) << endl;
} else if (choice == 0) {
cout << "계산기를 종료합니다!" << endl;
} else {
cout << "잘못된 선택입니다." << endl;
}
} while (choice != 0);
return 0;
}
🧠 추가 연습 - 반복하는 프로그램
구구단 연습 프로그램
#include <iostream>
using namespace std;
int main() {
int dan;
cout << "구구단 연습 프로그램" << endl;
cout << "0을 입력하면 종료됩니다." << endl;
while (true) {
cout << "몇 단을 출력할까요? ";
cin >> dan;
if (dan == 0) {
cout << "프로그램을 종료합니다." << endl;
break;
}
if (dan < 1 || dan > 9) {
cout << "1부터 9까지만 입력해주세요." << endl;
continue;
}
cout << "\n" << dan << "단:" << endl;
for (int i = 1; i <= 9; i++) {
cout << dan << " x " << i << " = " << dan * i << endl;
}
cout << endl;
}
return 0;
}
숫자 맞추기 게임
#include <iostream>
using namespace std;
int main() {
int secret = 7; // 정답
int guess;
int attempts = 0;
cout << "숫자 맞추기 게임! (1~10 사이의 숫자)" << endl;
do {
attempts++;
cout << attempts << "번째 시도 - 숫자를 입력하세요: ";
cin >> guess;
if (guess == secret) {
cout << "정답입니다! " << attempts << "번만에 맞추셨네요!" << endl;
} else if (guess < secret) {
cout << "더 큰 숫자입니다." << endl;
} else {
cout << "더 작은 숫자입니다." << endl;
}
} while (guess != secret);
return 0;
}
🎯 핵심 요약
while문과 do-while문 완벽 정리
구분 | while문 | do-while문 |
---|---|---|
실행 시점 | 조건 확인 후 실행 | 실행 후 조건 확인 |
최소 실행 횟수 | 0번 (조건이 처음부터 false면) | 1번 (무조건 한 번은 실행) |
적합한 상황 | 입력 검증, 반복 횟수 불명확 | 메뉴 시스템, 최소 1번 실행 필요 |
문법 | while (조건) { } | do { } while (조건); |
실무에서 자주 사용하는 패턴
-
입력 검증 패턴
while (input < min || input > max) { cout << "다시 입력하세요: "; cin >> input; }
-
메뉴 시스템 패턴
do { displayMenu(); choice = getUserChoice(); processChoice(choice); } while (choice != EXIT);
-
파일/데이터 처리 패턴
while (hasMoreData()) { data = readData(); processData(data); }
다음 토픽에서는 break와 continue를 활용한 반복문 제어와 중첩 반복문에 대해 자세히 알아보겠습니다! 🚀
Last updated on