Home [C++ 공부] 기초 - 조건문, 반복문
Post
Cancel

[C++ 공부] 기초 - 조건문, 반복문

코딩 뉴비의 공부 정리 및 기록용 포스트입니다.
잘못된 내용을 바로잡아주시면 감사하겠습니다.


C++ 조건문

if 조건문 (If Statement)


if 조건문은 조건이 참일 경우 내부의 코드를 실행한다.

1
2
3
if (condition) {
    // 조건이 참일 때 실행
}

예시


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;

int main() {
    int num1 = 10;
    int num2 = 20;

    if (num1 > num2) {
        cout << "num1 > num2" << endl;
    }

    if (num1 < num2) {
        cout << "num1 < num2" << endl;
    }
}

/* 
출력 :
num1 < num2
*/

else 조건문 (Else Statement)


else 구문은 if 조건문이 참이 아닐 때 내부의 코드를 실행한다.

1
2
3
4
5
if (condition) {
    // 참
} else {
    // 거짓
}

예시


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;

int main() {
    int num1 = 10;
    int num2 = 20;

    if (num1 == num2) {
        cout << "num1 == num2" << endl;
    } else {
        cout << "num1 != num2" << endl;
    }
}

/* 
출력 :
num1 != num2
*/

else if (Else if Statement)


처음 if 조건이 참이 아니고, else if 에 주어진 조건이 참일 때 내부 코드를 실행한다.

1
2
3
4
5
6
7
if (cond.1) {
    // cond.1 이 참이면 먼저 실행
} else if (cond.2) {
    // cond.1 이 거짓이고 cond.2 가 참일 때 실행
} else {
    // 두 조건이 모두 거짓이면 실행
}

예시


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;

int main() {
    int num1 = 10;
    int num2 = 20;

    if (num1 == num2) {
        cout << "num1 == num2" << endl;
    } else if (num1 < num2) {
        cout << "num1 < num2" << endl;
    } else {
        cout << "num1 > num2" << endl;
    }
}

/* 
출력 :
num1 < num2
*/

삼항 연산자 (Ternary Conditional Operator)


?: 의 삼항 연산자를 이용한 조건문 작성이 가능하다.

1
(조건문) ? expr.1 : expr.2;

expr.1은 조건문이 참일 때 실행되고, expr.2는 조건문이 거짓일 때 실행된다.

예시


1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
using namespace std;

int num = 1;
str_result = (num > 0) ? "num is positive" : "num is not positive";

cout << str_result;

/*
출력 : 
num is positive
*/

Switch 조건문 (Switch Statement)


1
2
3
4
5
6
7
8
9
10
switch(expr) {
    case x:
        // 코드 블럭
        break;
    case y:
        // 코드 블럭
        break;
    default:
        // 코드 블럭
}

예시


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using namespace std;

int a = 3;
switch(a) {
    case 1:
        cout << "1";
        break;
    case 2:
        cout << "2";
        break;
    case 3:
        cout << "3";
        break;
    default:
        cout << "?";
        break;
}

/* 
출력 :
3
*/

default 이하의 코드는 주어진 값이 어떤 case 에도 해당하지 않을 경우 작동한다.

C++ 반복문

While 반복문


조건이 만족될 때까지 코드를 반복 실행하는 구문이다.

1
2
3
while (cond.) {
    // 코드 블럭
}

예시


1
2
3
4
5
6
7
8
9
10
11
12
13
14
int i = 0;
while (i < 5) {
    cout << i << endl; // i를 출력하고 줄바꿈
    i++; // i를 1만큼 증가
} 

/* 
출력 :
0
1
2
3
4
*/

do/while 반복문


while 문의 변형 형태로 do 코드 블럭 내부를 반복 실행한다.

1
2
3
4
do {
    // 코드 블럭
}
while (cond.);

예시


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int i = 0;
do {
  cout << i << "\n";
  i++;
}
while (i < 5);

/* 
출력 :
0
1
2
3
4
*/

for 반복문


반복 횟수를 미리 정하여 실행하는 구문이다.

예시


1
2
3
4
5
for (int i = 0; i < 10; ++i) {
    // 코드 블럭
}

// 10번 반복 실행됨

첫번째 부분에는 변수를 선언한다. 이미 선언된 변수는 다시 선언할 필요가 없다.

두번째 부분에는 반복이 실행될 조건을 정의한다. 조건이 참일 때, 반복이 실행되고 조건이 거짓이면 반복이 종료된다.

세번째 부분에는 변수의 값을 증가/감소한다. 이는 반복이 끝날 때마다 실행된다.

이중 for문


for문 안에 for문을 넣어 반복문을 구성할 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
for (int i = 1; i <= 3; ++i) {
    cout << "Class: " << i << "\n";
    for (int j = 1; j <= 3; ++j) {
        cout << "Number: " << j << "\n";
    }
}

/* 
출력 :
Class: 1
Number: 1
Number: 2
Number: 3
Class: 2
Number: 1
Number: 2
Number: 3
Class: 3
Number: 1
Number: 2
Number: 3
*/

바깥의 for문이 1번 반복되는 동안 안쪽의 for문은 3번 반복된다.

foreach 반복문


다음과 같이 배열 내의 요소를 반복하는 구문을 구성할 수 있다.

1
2
3
for (type variableName : arrayName) {
    // 코드 블럭
}

예시


1
2
3
4
5
6
7
8
9
int arr[5] = {1, 2, 3, 4, 5};
for (int i : arr) {
    cout << i;
}

/* 
출력 :
12345
*/

Continue


continue 는 해당 반복 과정을 스킵한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
for (int = 0; i < 10; ++i) {
    if (i == 4)
        continue;
    cout << i << endl;
}

/* 
출력 :
0
1
2
3
5
6
7
8
9
10
*/

Break


break 는 조건과 관계없이 반복문을 종료한다. 주로 특정 조건 하에서 break를 사용한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
for (int i = 0; i < 10; ++i) {
    if (i == 4) {
        break;
    }
    cout << i << endl;
}

/* 
출력 :
0
1
2
3
*/

위 예시에서 i4가 되었을 때, 출력문보다 break가 먼저 실행되므로 4는 출력되지 않는다.


Useful Link


C++ Conditions
C++ Switch
C++ While Loop
C++ For Loop
C++ Break/Continue

This post is licensed under CC BY 4.0 by the author.