[코테]/[GroomEdu]
[COS PRO 2급] 5차 2번_공강시간 구하기 (C/C++)
Sky_
2021. 5. 23. 16:00
주어진 코드
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
int func_a(int time_table[], int time_table_len) {
int answer = 0;
for (int i = time_table_len - 1; i >= 0; i--) {
if (time_table[i] == 1) {
answer = i;
break;
}
}
return answer;
}
int func_b(int time_table[], int class1, int class2) {
int answer = 0;
for (int i = class1; i < class2; i++)
if (time_table[i] == 0)
answer++;
return answer;
}
int func_c(int time_table[], int time_table_len) {
int answer = 0;
for (int i = 0; i < time_table_len; i++) {
if (time_table[i] == 1) {
answer = i;
break;
}
}
return answer;
}
int solution(int time_table[], int time_table_len) {
int answer = 0;
int first_class = ; //빈칸
int last_class = ; //빈칸
answer = ; //빈칸
return answer;
}
int main() {
int time_table[] = { 1, 1, 0, 0, 1, 0, 1, 0, 0, 0 };
int time_table_len = 10;
int ret = solution(time_table, time_table_len);
printf("solution 함수의 반환 값은 %d 입니다.\n", ret);
}
완성 코드
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
int func_a(int time_table[], int time_table_len) {
int answer = 0;
for (int i = time_table_len - 1; i >= 0; i--) {
if (time_table[i] == 1) {
answer = i;
break;
}
}
return answer;
}
int func_b(int time_table[], int class1, int class2) {
int answer = 0;
for (int i = class1; i < class2; i++)
if (time_table[i] == 0)
answer++;
return answer;
}
int func_c(int time_table[], int time_table_len) {
int answer = 0;
for (int i = 0; i < time_table_len; i++) {
if (time_table[i] == 1) {
answer = i;
break;
}
}
return answer;
}
int solution(int time_table[], int time_table_len) {
int answer = 0;
int first_class = func_c(time_table, time_table_len);
int last_class = func_a(time_table, time_table_len);
answer = func_b(time_table, first_class, last_class);
return answer;
}
int main() {
int time_table[] = { 1, 1, 0, 0, 1, 0, 1, 0, 0, 0 };
int time_table_len = 10;
int ret = solution(time_table, time_table_len);
printf("solution 함수의 반환 값은 %d 입니다.\n", ret);
}
예시
time_table | time_table_len | return |
[1, 1, 0, 0, 1, 0, 1, 0, 0, 0] | 10 | 3 |
코드 분석
단계 | 과정 |
main | 시간별 수업 여부가 담겨있는 배열 time_table과 그 길이 time_table_len을 선언한다. |
solution | 공강의 갯수를 셀 변수 answer를 0으로 초기화한다. |
func_c solution |
가장 첫 수업 시작시간을 구하기 위해 func_c함수를 호출한다. 첫 수업 시작시간(func_c함수의 반환값)이 변수 first_class에 저장된다. |
func_a solution |
가장 마지막 수업 시작시간을 구하기 위해 func_a함수를 호출한다. 마지막 수업 시작시간(func_a함수의 반환값)이 변수 last_class에 저장된다. |
func_b | func_c단계와 func_a단계의 값 사이에 공강이 있는지 확인하기 위해 func_b함수를 호출한다. for문을 통해 수업 시작 시간에서 마지막 시간까지 반복한 후, time_table배열의 각 값이 0일 때 answer++를 통해 공강의 횟수를 센다. |
solution | func_b의 반환값을 return한다. |
main | 결과를 출력한 후 프로그램이 종료된다. |
goorm
구름은 클라우드 기술을 이용하여 누구나 코딩을 배우고, 실력을 평가하고, 소프트웨어를 개발할 수 있는 클라우드 소프트웨어 생태계입니다.
www.goorm.io