티스토리 뷰

다음 코드의 출력 결과는 무엇인가?

#include <iostream>
#include <string>
using namespace std;

int main() {

    string a = "Hello";
    string b = "World";

    cout << a + " " + b << endl;

}

Hello World


문제 2 (참조 호출)

#include <iostream>
using namespace std;

void change(int x) {
    x = 10;
}

int main() {

    int a = 5;

    change(a);

    cout << a << endl;

}

5

call by value 이기 때문이다.
함수 안에서 값이 바뀌어도 원본은 바뀌지 않는다.


문제 3 (반복문)

#include <iostream>
using namespace std;

int main() {

    int sum = 0;

    for(int i = 1; i <= 5; i++){
        sum += i;
    }

    cout << sum << endl;

}

15


문자열 연결

다음 코드의 출력 결과는 무엇인가?

#include <iostream>
#include <string>
using namespace std;

int main() {

    string a = "Data";
    string b = "Structure";

    cout << a + " " + b << endl;

}

Data Structure


조건문

다음 코드의 출력 결과는 무엇인가?

#include <iostream>
using namespace std;

int main() {

    int num = -3;

    if(num > 0)
        cout << "positive";
    else
        cout << "negative";

}

negative

함수 (call by value)

#include <iostream>
using namespace std;

void change(int x){
    x = 20;
}

int main(){

    int a = 5;

    change(a);

    cout << a << endl;

}

5: 값에 의한 호출(call by value)이므로 함수 내부에서 값이 변경되어도 원래 변수는 변하지 않는다.

함수 (call by reference) (시험 단골)

#include <iostream>
using namespace std;

void change(int &x){
    x = 20;
}

int main(){

    int a = 5;

    change(a);

    cout << a << endl;

}

20: 참조 호출(call by reference)은 실제 변수의 값을 변경한다.

반복문 실행 횟수

다음 반복문의 실행 횟수는 몇 번인가?

for(int i = 0; i < 10; i++){
    cout << i << endl;
}

10번

동적 메모리 할당

다음 코드에서 동적으로 할당된 메모리를 해제하는 명령어는 무엇인가?

int *p = new int;

delete p;

C++은 garbage collection이 없기 때문에 동적으로 할당한 메모리는 직접 해제해야 한다.

시간복잡도

다음 코드의 시간복잡도를 작성하여라.

for(int i = 0; i < n; i++){
    cout << i;
}

O(n) : 입력 크기 n에 비례하여 반복문이 실행된다.

이중 반복문 시간복잡도

다음 코드의 시간복잡도를 작성하여라.

for(int i = 0; i < n; i++){
    for(int j = 0; j < n; j++){
        cout << i << j;
    }
}

O(n²): 두 개의 반복문이 중첩되어 실행되기 때문에 수행 횟수는 n×nn \times n 이 된다.


다음 프로그램의 출력 결과와 시간복잡도를 작성하여라.

#include <iostream>
using namespace std;

int main() {

    int count = 0;

    for(int i = 0; i < n; i++){
        for(int j = 0; j <= i; j++){
            count++;
        }
    }

    cout << count << endl;

}
i = 0 → 1번
i = 1 → 2번
i = 2 → 3번
...
i = n-1 → n번

1 + 2 + 3 + ... + n = O(n²)

하지만 내부 반복문이 i에 따라 증가하기 때문에, 이차 시간복잡도가 된다.


정리

1. for 반복문 계산
2. string 연결
3. call by value / reference
4. new / delete
5. 시간복잡도 O(n), O(n²)

반응형
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2026/03   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
글 보관함