함수는 입력을 받아 처리한 뒤에 출력하는 구조를 가집니다
함수는 소스코드가 반복되는 것을 줄이도록 해줍니다
반환 자료형 함수명(매개변수){
return 반환할 값;
}
함수를 활용해 특정한 말머리를 출력하는 예시
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
#include <stdio.h>
void dice(int input) {
printf("던진 주사위: %d\n", input);
}
int main(void) {
dice(3);
dice(5);
dice(1);
system("pause");
return 0;
}
|
cs |
함수를 활용해 더하기를 출력하는 예시
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
int main(void) {
printf("%d\n", add(10, 20));
printf("%d\n", add(50, -30));
printf("%d\n", add(70, 125));
system("pause");
return 0;
}
|
cs |
함수를 활용해 사칙연산을 출력하는 예시
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
#include <stdio.h>
void calculator(int a, int b) {
printf("%d + %d = %d\n", a, b, a + b);
printf("%d - %d = %d\n", a, b, a - b);
printf("%d * %d = %d\n", a, b, a * b);
printf("%d / %d = %d\n", a, b, a / b);
printf("\n");
}
int main(void) {
calculator(10, 3);
calculator(15, 2);
calculator(18, 4);
system("pause");
return 0;
}
|
cs |
함수를 활용하면 보다 깔끔하고 간결한 프로그래밍이 가능합니다
재귀 함수
자기 자신을 포함하는 함수입니다
반드시 재귀 종료 조건이 필요합니다
재귀 함수를 이용한 팩토리얼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int factorial(int a) {
if (a == 1) return 1;
else return a * factorial(a - 1);
}
int main(void) {
int n;
printf("n 팩토리얼을 계산합니다");
scanf("%d", &n);
printf("%d\n", factorial(n));
system("pause");
return 0;
}
|
cs |
이때 무한 루프가 발생하지 않게 종료 조건을 잘 설정하는 것이 중요합니다