과제 6 - Function (6 ~ 9)
함수를 통한 swap을 구현하는 문제이다.
#include <stdio.h>
int x, y = 0; // declare x, y with global variable
void swap(int n1, int n2){ // swapping
x = n2;
y = n1;
return;
}
int main(){
// input value of x, y(global variable)
printf("Enter Value of x\n");
scanf("%d", &x);
printf("Enter Value of y\n");
scanf("%d", &y);
swap(x, y); // using function
printf("After Swapping: x = %d, y = %d\n", x, y); // printing output
return 0;
}
포인터를 사용하지 않아 전역변수로 x, y값을 선언했다.
만약 local variable로 x, y를 선언했다면 call by value가 되어 swap함수 이후에도 x, y값은 그대로였을 것이다.
수를 입력받아 팩토리얼을 구현하는 문제이다.
#include <stdio.h>
int Factorial(int n){
// implementing factorial
if(n == 1)
return n; // if n == 1 -> return 1
else
return Factorial(n-1) * n; // return n * (n-1)!
}
int main(){
int n;
printf("Enter number: ");
scanf("%d", &n); // getting input number from user
printf("%d", Factorial(n)); // printing output
return 0;
}
1일 경우 1을 리턴, 1이 아닐 경우 재귀적으로 함수를 진행한다.
또한 int값을 반환하기 때문에 컴파일 에러가 발생하지 않도록 무조건 int형 변수를 리턴하여 함수를 탈출할 수 있도록 주의해야 한다.
1부터 99999까지의 합을 register variable을 통해 출력하는 프로그램이다.
#include <stdio.h>
int main(){
register int i = 0;
long long s = 0; // representing sum of 1 to 99999 with register variable
for(i=1; i<100000; i++){
s += i;
}
printf("%lld\n", s); // printing output
return 0;
}
register int 타입인 i를 초기화한 후 큰 값을 담을 변수인 long long형 타입을 초기화한다.
그리고 for문을 통해 값을 구하고, %lld를 통해 결과값을 출력한다.
long long, %d, register int를 잘 몰랐기 때문에 꽤 많이 검색했던 것 같다.
재귀를 통한 피보나치를 구현하는 문제이다.
#include <stdio.h>
int Fibonacci(int n){
if(n == 1)
return 0; // F0 = 1
else if(n <= 3)
return 1; // F1 and F2 = 1
else
return Fibonacci(n-1) + Fibonacci(n-2); // F(n) = F(n-1) + F(n-2)
}
int main(){
int n=0;
printf("Enter any number to find nth fibonacci term:");
scanf("%d", &n); // getting input from user
printf("%d fibonacci term is %d", n, Fibonacci(n)); // printing output
return 0;
}
값이 1일 경우, 3 이하일 경우, 이외의 경우르 나누어 구현하는 것이 중요하다.
F3 = F1 + F2라는 특성을 재귀를 통해 구현하였다.
개인적으로 재귀함수는 메모리도 많이 먹고 머리를 더 많이 사용하는지라 예전에는 그냥 for문으로 문제를 풀었다.
그치만 자료구조에서의 단골손님인 하노이의 탑을 구현해야 하기 때문에 어려워도 재귀는 익숙해지는게 좋은것같다.
지난 컴구에서 메모리 이동에서 꽤 애를 먹었던 기억이 있기에...