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

[정보처리기사 실기] 2022년 2회 17 - 프로그래밍 [JAVA]

쏠솔랄라 2025. 7. 23. 14:14

 

 

 

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

class Test {
	public static void main(String args[]) {
		cond obj = new cond(3);
		obj.a=5;
		int b=obj.func();
		System.out.print(obj.a+b);
	}
}

class cond {
	int a;
	public cond(int a) {
		this.a=a;
	}
	public int func() {
		int b=1;
		for(int i=1; i<a; i++)
			b += a*i;
		return a+b;
	}
}

 

 

 

 

 

 

해설

코드 실행순서 및 해석
1 class Test {    
2      public static void main(String args[]) { 1 실행
3           cond obj = new cond(3); 2 obj 객체변수 생성
4           obj.a=5; 6 obj.a에 5를 넣음
5           int b=obj.func(); 7
13
func() 메소드 호출
b=56
6           System.out.print(obj.a+b); 14 5+56=61
7      }    
8 }    
9 class cond {    
10      int a; 3 obj의 객체변수의 멤버변수 a 생성
11      public cond(int a) { 4 생성자 cond(3)으로 실행
12      this.a=a; 5 this.a=3 : 현재의 obj의 a에 3을 넣는다
13 }    
14 public int func() { 8 호출
15      int b=1; 9 정수값 b를 선언하고 1로 초기화
16      for(int i=1; i<a; i++) 10 a의 값은 5이므로 0-4 반복
17      b += a*i; 11 51
18      return a+b; 12 5+51=56
19      }    
20 }    

 

obj func
a i b b=b+(a*i)
3 1 1 1+5*1=6
5 2 6 6+5*2=16
  3 16 16+5*3=31
  4 31 31+5*4=51