first commit

This commit is contained in:
2021-03-02 09:35:46 +08:00
commit e1f560dc02
3 changed files with 120 additions and 0 deletions

31
week1/task1.c Normal file
View File

@@ -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 <stdio.h>
#include <assert.h>
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);
}

41
week1/task2.c Normal file
View File

@@ -0,0 +1,41 @@
/*
* Author: Walter
* Student ID: 1930006025
* Week_1_Task_2
* Read in and reverse a string using recursion
*/
#include <stdio.h>
#include <assert.h>
#include <string.h>
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);
}

48
week1/task3.c Normal file
View File

@@ -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 <stdio.h>
#include <assert.h>
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);
}