commit e1f560dc02af5400094a5d2aa161822242c7b029 Author: heimoshuiyu Date: Tue Mar 2 09:35:46 2021 +0800 first commit diff --git a/week1/task1.c b/week1/task1.c new file mode 100644 index 0000000..57b9975 --- /dev/null +++ b/week1/task1.c @@ -0,0 +1,31 @@ +/* + * Author: Walter + * Student ID: 1930006025 + * Week_1_Task_1 + * Read in a positive number and compute its factorial using resursion + */ + +#include +#include + +long int factR(int n); + +int main() { + int n; + printf("Enter a positive number to get its factorial\n"); + scanf("%d", &n); + printf("Result is %ld\n", factR(n)); + return 0; +} + +long int factR(int n) { + /* check */ + assert(n > 0); + + /* end of recursion */ + if (n == 1) { + return 1; + } + + return n * factR(n-1); +} diff --git a/week1/task2.c b/week1/task2.c new file mode 100644 index 0000000..be96566 --- /dev/null +++ b/week1/task2.c @@ -0,0 +1,41 @@ +/* + * Author: Walter + * Student ID: 1930006025 + * Week_1_Task_2 + * Read in and reverse a string using recursion + */ + +#include +#include +#include + +void reverseR(char * str, int length); + +int main() { + char str[50]; + printf("Enter a string: "); + scanf("%s", str); + reverseR(str, strlen(str)); + printf("Result: %s\n", str); + return 0; +} + +void reverseR(char *str, int length) { + /* check */ + assert(length <= 50); + assert(length >= 0); + + /* end of recursion */ + if (length <= 1) { + return; + } + + /* recursion */ + char tmp; + tmp = str[0]; + str[0] = str[length-1]; + str[length-1] = tmp; + + /* str move forward, length decrese 2 char */ + reverseR(str+1, length-2); +} diff --git a/week1/task3.c b/week1/task3.c new file mode 100644 index 0000000..a414450 --- /dev/null +++ b/week1/task3.c @@ -0,0 +1,48 @@ +/* + * Author: Walter + * Student ID: 1930006025 + * Week_1_Task_3 + * Read in and compute the greatest common divisor (GCD) of + * two natural numbers using recursion + */ + +#include +#include + +int GCD(int x, int y); + +/* the real GCD function */ +int _GCD(int x, int y); + +int main() { + int x, y; + printf("Please input x\n"); + scanf("%d", &x); + printf("Please input y\n"); + scanf("%d", &y); + printf("Result is %d\n", GCD(x, y)); + return 0; +} + +int GCD(int x, int y) { + /* check x y are natural numbers */ + assert(x >= 0); + assert(y >= 0); + + /* make sure x >= y, + * then call the read GCD function */ + if (x >= y) { + return _GCD(x, y); + } else { + return _GCD(y, x); + } +} + +int _GCD(int x, int y) { + /* end of recursion */ + if (y == 0) { + return x; + } + + return _GCD(y, x % y); +}