본문 바로가기
자격증공부/정보처리기사

[정처기] C언어 제어문

by jyee 2023. 9. 21.
728x90
반응형

 

문제 1

 

#include <stdio.h>
main() {
	int score[] = { 86, 53, 95, 76, 61} ;
	char grade;
	char str[] = "Rank";
	for (int i = 0; i < 5; i++){
		switch (score[i] / 10) {
			case 10:
			case 9:
				grade = 'A';
				break;
			case 8:
				grade = 'B';
				break;
			case 7:
				grade = 'C';
				break;
			default: grade ='F';
		}
		if (grade != 'F')
		printf("%d is %c %s\n", i + 1, grade, str);
	}
	
}

 

풀이 

5개의 배열이 만들어짐  

 

score

{   0             1              2            3             4    }

86 53 95 76 61

각각 이 위치에 초기값이 들어가는데 

 

str

{   0             1              2            3             4    }

R a n k /0

 

for (int i =0; i<5; i++) { 

이제 for문을 돌릴 때, 초기 값은 0 이고 반복값 5미만일 때 

switch문 반복실행 하게 되면 

먼저 score[i]/10을 했을 때 

 

i score[i]  score[i] /10 grade grade!=' F' 출력
0 86 8 B 1 is B Rank
1 53 5 F 거짓  
2 95 9 A 3 is A Rank
3 76 7 C 4 is C Rank 
4 61 6 F 거짓  
5          


 

문제 5

 

#include <stdio.h>
main() {
	int c = 1;
	switch (3) {
		case 1: c += 3;
		case 2: c++;
		case 3: c = 0;
		case 4: c += 3;
		case 5: c -= 10;
		default: c--;
	}
	printf("%d", c);
}

 

풀이

초기값으로 1을 넣고 시작하면 

그다음 switch (3)이니깐

case 3으로 넘어

c
1
0
3
-7
-8
print -8

그다음 break가 따로 없으니깐 

case 4로 넘어가면 c = c+3 

case 5로 넘어가면 c = c - 10

default는 c-- 즉, c의 값에서 -1을 감소시켜라

답은 -8


 

 

문제 6

#include <stdio.h>
main() {
	int a = 3, b = 10;
	if (b > 5)
		printf("%x\n", a + b);
	else
		printf("%x\n", b - a);
}

풀이

if조건이 만족했을 때 참과 거짓 나오는 것 

10> 5 일 때 결과 참일 때 

%x가 16진수로 출력해라는것 그래서 a + b=  3 +10 으로 나옴 

16진수 

0~ 15 중 1~9만 숫자고 10(A) 11(B) 12(C) 13(D), 14(E), 15(F)

그래서 D로 나옴 

 

else로 넘어가면 

b - a = 10 - 3 

이래서 7로 나올것인데 

결과가 참이기 때문에  출력되는 값은 d로 나오는것 


 

문제 7

#include <stdio.h>
main() {
	int s, el = 0;
	for (int i = 6; i <= 30; i++) {
		s = 0;
		for (int j = 1; j <= i /2; j++)
		if ( i % j == 0 )
			s = s + j;
		if ( s == i )
			el++;
	}
	printf("%d", el);
}

 

풀이

첫번째 for문과 두번째 for문이 있다는 것을 알아야함 

 

 

728x90
반응형