정보처리기사 실기C언어C - 재귀함수와 구조체난이도 5SHORT_ANSWER

정보처리기사 실기 C - 재귀함수와 구조체 기출문제 #348

문제

다음 C 코드의 실행 결과를 쓰시오.

C
#include <stdio.h> typedef struct { int a, b, cnt; } Data; void process(Data d, int depth) { if (depth <= 0) { printf("%d ", d.a * d.b); return; } if (d.cnt % 2 == 0) { Data next1 = {d.a + depth, d.b - 1, d.cnt + 1}; Data next2 = {d.a - 1, d.b + depth, d.cnt + 2}; process(next2, depth - 1); process(next1, depth - 2); } else { Data next1 = {d.a * 2, d.b + 1, d.cnt + 1}; Data next2 = {d.a + 1, d.b * 2, d.cnt + 2}; process(next1, depth - 1); process(next2, depth - 2); } } int main() { Data start = {2, 3, 0}; process(start, 3); return 0; }

정답

-9 7 15 30 24

-9 7 15 30 24-9 7 15 30 24-9 7 15 30 24

해설

단계별 실행 추적 (호출 순서대로):

  1. process({2,3,0}, 3): cnt=0(짝수)

    • next1 = {2+3, 3-1, 0+1} = {5, 2, 1}
    • next2 = {2-1, 3+3, 0+2} = {1, 6, 2}
    • process({1,6,2}, 2) 먼저 실행
    • process({5,2,1}, 1) 나중 실행
  2. process({1,6,2}, 2): cnt=2(짝수)

    • next1 = {1+2, 6-1, 2+1} = {3, 5, 3}
    • next2 = {1-1, 6+2, 2+2} = {0, 8, 4}
    • process({0,8,4}, 1) 먼저 실행
    • process({3,5,3}, 0) 나중 실행
  3. process({0,8,4}, 1): cnt=4(짝수)

    • next1 = {0+1, 8-1, 4+1} = {1, 7, 5}
    • next2 = {0-1, 8+1, 4+2} = {-1, 9, 6}
    • process({-1,9,6}, 0) 먼저 실행 → depth=0이므로 출력: "-9 "
    • process({1,7,5}, -1) 나중 실행 → depth≤0이므로 출력: "7 "
  4. process({3,5,3}, 0): depth=0이므로 출력: "15 "

  5. process({5,2,1}, 1): cnt=1(홀수)

    • next1 = {5*2, 2+1, 1+1} = {10, 3, 2}
    • next2 = {5+1, 2*2, 1+2} = {6, 4, 3}
    • process({10,3,2}, 0) 먼저 실행 → depth=0이므로 출력: "30 "
    • process({6,4,3}, -1) 나중 실행 → depth≤0이므로 출력: "24 "

출력 순서: -9 → 7 → 15 → 30 → 24 따라서 최종 출력: "-9 7 15 30 24"

이런 문제 20~50개를 한 번에 풀어보세요

매번 새로 추가되는 모의고사 + 오답 자동 복습 + 회차별 실력 추적. 회원가입 후 무료 이용.