include stdio h include stdlib h include time
#include <stdio. h> #include <stdlib. h> #include <time. h> 반복과 순환의 비교 double slow_power(double x, int n) { int i; } int main(void) { double x, value_slow, value; int n; double r = 1. 0; x = 2; n = 10; for (i = 0; i < n; i++) r = r * x; return (r); value_slow = slow_power(x, n); value = power(x, n); double power(double x, int n) { } if (n == 0) return 1; else if ((n % 2) == 0) return power(x*x, n / 2); else return x * power(x*x, (n - 1) / 2); } printf("slow_power(%lf, %d) = %lf n", x, n, value_slow); printf("power(%lf, %d) = %lf n", x, n, value);
#include <stdio. h> #include <stdlib. h> double power(double x, int n) { double value, result; } printf("call power(%lf, %d) n", x, n); if (n == 0) { printf("return 1n"); return 1; } else if ((n % 2) == 0) { value = power(x*x, n / 2); printf("return %lf n", value); return value; } else { value = power(x*x, (n - 1) / 2); result = x * value; printf("return %lf * %lf n", x, value); return result; } int main(void) 순환의 호출과 { double x, value_slow, value; int n; 리턴 x = 2; n = 10; value = power(x, n); } printf("power(%lf, %d) = %lf n", x, n, value);
합의 반복 및 순환 버전 #include <stdio. h> int sum_iter(int n) { int i, sum=0; } for(i=1; i<=n; i++) sum += i; return sum; int sum_rc(int n) { if(n == 1) return 1; else return n+sum_rc(n-1); } int main(void) { int result; result = sum_iter(10); printf("sum_iter(10) = %d n", result); } result = sum_rc(10); printf("sum_rc(10) = %d n", result);
문자열 역순 출력 #include <stdio. h> char hello[20] = "Hello world!!!"; void print_char(char hello[], int n) { if(hello[n] != NULL) print_char(hello, n+1); else return; putchar(hello[n]); } int main(void) { print_char(hello, 0); }
- Slides: 4