문제
다음 C 코드의 실행 결과를 쓰시오.
C#include <stdio.h> typedef struct { int x, y; } Point; void process(Point p, int depth) { if (depth <= 0) { printf("%d ", p.x + p.y); return; } Point left = {p.x + 1, p.y + 1}; Point right = {p.x - 1, p.y + 1}; process(right, depth - 1); printf("%d ", p.x * p.y); process(left, depth - 1); } int main() { Point start = {2, 1}; process(start, 2); return 0; }
정답
3 2 5 2 5 6 7
3 2 5 2 5 6 73 2 5 2 5 6 7
해설
process({2,1}, 2) 호출:
- right = {1,2}, left = {3,2}
- process({1,2}, 1) 호출:
- right = {0,3}, left = {2,3}
- process({0,3}, 0): depth<=0이므로 printf(0+3) → '3' 출력
- printf(1*2) → '2' 출력
- process({2,3}, 0): depth<=0이므로 printf(2+3) → '5' 출력
- printf(2*1) → '2' 출력
- process({3,2}, 1) 호출:
- right = {2,3}, left = {4,3}
- process({2,3}, 0): depth<=0이므로 printf(2+3) → '5' 출력
- printf(3*2) → '6' 출력
- process({4,3}, 0): depth<=0이므로 printf(4+3) → '7' 출력
따라서 출력 순서: 3 2 5 2 5 6 7