728x90
반응형
개요
C++에서 흐름 제어(Control Flow)는 프로그램의 실행 흐름을 제어하여 논리적인 분기, 반복, 또는 특정 조건에서 코드 실행을 가능하게 합니다. 이 문서에서는 C++에서 제공하는 주요 흐름 제어 문법과 사용법을 설명합니다.
흐름 제어의 종류
C++의 흐름 제어는 크게 다음 세 가지로 나뉩니다:
조건문
반복문
점프문
1. 조건문 (Conditional Statements)
조건문은 특정 조건에 따라 코드 블록을 실행하거나 건너뛰도록 제어합니다.
1.1 if 문
#include <iostream>
using namespace std;
int main() {
int age = 18;
if (age >= 18) {
cout << "You are an adult." << endl;
}
return 0;
}
1.2 if-else 문
#include <iostream>
using namespace std;
int main() {
int number;
cout << "Enter a number: ";
cin >> number;
if (number % 2 == 0) {
cout << "The number is even." << endl;
} else {
cout << "The number is odd." << endl;
}
return 0;
}
1.3 if-else if-else 문
#include <iostream>
using namespace std;
int main() {
int score;
cout << "Enter your score: ";
cin >> score;
if (score >= 90) {
cout << "Grade: A" << endl;
} else if (score >= 80) {
cout << "Grade: B" << endl;
} else if (score >= 70) {
cout << "Grade: C" << endl;
} else {
cout << "Grade: F" << endl;
}
return 0;
}
1.4 switch 문
#include <iostream>
using namespace std;
int main() {
int day;
cout << "Enter a day number (1-7): ";
cin >> day;
switch (day) {
case 1:
cout << "Monday" << endl;
break;
case 2:
cout << "Tuesday" << endl;
break;
case 3:
cout << "Wednesday" << endl;
break;
case 4:
cout << "Thursday" << endl;
break;
case 5:
cout << "Friday" << endl;
break;
case 6:
cout << "Saturday" << endl;
break;
case 7:
cout << "Sunday" << endl;
break;
default:
cout << "Invalid day number." << endl;
}
return 0;
}
2. 반복문 (Loops)
반복문은 특정 코드 블록을 반복적으로 실행합니다.
2.1 for 문
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
cout << "Iteration: " << i << endl;
}
return 0;
}
2.2 while 문
#include <iostream>
using namespace std;
int main() {
int count = 1;
while (count <= 5) {
cout << "Count: " << count << endl;
count++;
}
return 0;
}
2.3 do-while 문
#include <iostream>
using namespace std;
int main() {
int number;
do {
cout << "Enter a positive number: ";
cin >> number;
} while (number <= 0);
cout << "You entered: " << number << endl;
return 0;
}
3. 점프문 (Jump Statements)
점프문은 코드의 실행 흐름을 특정 위치로 이동시킵니다.
3.1 break 문
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break;
}
cout << i << endl;
}
return 0;
}
3.2 continue 문
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
cout << i << endl;
}
return 0;
}
3.3 goto 문
#include <iostream>
using namespace std;
int main() {
int x = 1;
start:
cout << x << endl;
x++;
if (x <= 5) {
goto start;
}
return 0;
}
결론
C++의 흐름 제어 문법은 프로그램 실행의 논리적 흐름을 제어하는 데 중요한 역할을 합니다. 조건문, 반복문, 점프문을 적절히 활용하면 복잡한 문제를 효과적으로 해결할 수 있습니다.
728x90
'programming language > C++' 카테고리의 다른 글
C++ 복합데이터 (0) | 2025.01.13 |
---|---|
C++ 연산자 (0) | 2025.01.13 |
C++ 입출력 (0) | 2025.01.13 |
C++ 자료형 (0) | 2025.01.13 |
CLion ( JetBrains의 C/C++ IDE ) (0) | 2025.01.09 |