자격증/정보처리기사 실기 - 기출문제

[정보처리기사 실기] 2020년 4회 19 - 프로그래밍 [JAVA]

쏠솔랄라 2025. 7. 14. 11:12

 

 


19 다음 JAVA로 구현된 프로그램을 분석하여 그 실행 결과를 쓰시오. (단, 출력문의 출력 서식을 준수하시오.)

class Parent {
	int compute(int num) {
    	if(num <= 1) return num;
        return compute(num-1) + compute(num-2);    
    }
}
class Child extends Parent {
	int compute(int num) {
    	if(num<=1) return num;
        return compute(num-1) + compute(num-3);
    }
}

publlic class Test {
	public static void main() {
    	Parent obj = new Child();
        System.out.print(obj.compute(4));
    }
}

 

 

 

 

 

 

해설

코드 실행순서 및 해석
1 class Parent {    
2      int compute(int num) {    
3           if(num <= 1) return num;    
4           return compute(num-1) + compute(num-2);        
5      }    
6 }    
7 class Child extends Parent {   자식 클래스
8
     int compute(int num) {   부모 메서드와 자료형과 이름, 인수가 완전히 같음
-> 부모로부터 메서드를 물려받아 재정의함
4 실행
int compute(4)
9           if(num<=1) return num; 5 num이 1보다 작아질 때까지 반복
10           return compute(num-1) + compute(num-3); 6 compute(4-1)+compute(4-3)
-> compute(3)+compute(1)
-> num이 1이 될 때까지 8-10줄 반복
재귀함수: 자기자신을 호출
11      }    
12 }    
13 publlic class Test {    
14      public static void main() { 1 실행
15           Parent obj = new Child(); 2 개체변수 선언: Child() 메서드로 형 변환
16           System.out.print(obj.compute(4)); 3 compute(4)호출
17      }    
18 }    

 

compute(4)
compute(4-1)=compute(3) compute(4-3)=compute(1)
compute(3-1)=compute(2) compute(3-3)=compute(0) 1
compute(2-1)=compute(1) compute(2-3)=compute(-1) 0  
1 -1