메뉴 건너뛰기

C++ 기초 - break와 continue

Eugene 2026.03.30 16:21 조회 수 : 9

#include <iostream>
using namespace std;

int main() {
    unsigned int count;

    for (count = 1; count <= 10; count++) {
    if (count == 5) {
        break;
    }

    cout << count << " ";
    }

    cout << "\nBroke out of loop at count = " << count << endl;
}

 

위 프로그램의 결과는 아래와 같다.

 

1 2 3 4

Broke out of loop at count = 5

 

즉 10회 반복해야 할 for 문에서 count = 5 되었을 때, 조건문에서 break 명령이 실행되어 반복문이 중지되는 것이다.

 

#include <iostream>
using namespace std;

int main() {
    for (unsigned int count{1}; count <= 10; count++) {
        if (count == 5) {

        }

        cout << count << " ";
    }

    cout << "\nUsed continue to skip printing 5" << endl;
}

 

이번 프로그램의 결과는 아래와 같다.

 

1 2 3 4 6 7 8 9 10

Used continue to skip printing 5

 

결과에서 보면, 1 ~ 10까지의 숫자 중 5가 출력되지 않았다

조건문에서 5의 경우 continue문이 실행되어, continue문 아래 명령어가 실행되지 않고, 다음 반복으로 진행되기 때문이다.