diff --git a/semester1/pset13/2-1-malloc.c b/semester1/pset13/2-1-malloc.c new file mode 100644 index 0000000..cf8f5c1 --- /dev/null +++ b/semester1/pset13/2-1-malloc.c @@ -0,0 +1,24 @@ +#include +#include + +int main(void) { + int n; + scanf("%d", &n); + int *arr = malloc(n * sizeof(int)); + + for (int i = 0; i < n; i++) { + scanf("%d", &arr[i]); + } + + for (int i = 0; i < n; i++) { + arr[i] = arr[i] * -10; + } + + for (int i = 0; i < n - 1; i++) { + printf("%d ", arr[i]); + } + printf("%d\n", arr[n - 1]); + + free(arr); + return 0; +} diff --git a/semester1/pset13/2-2-malloc2d.c b/semester1/pset13/2-2-malloc2d.c new file mode 100644 index 0000000..67c4322 --- /dev/null +++ b/semester1/pset13/2-2-malloc2d.c @@ -0,0 +1,32 @@ +#include +#include + +int main(void) { + int row, col; + scanf("%d%d", &row, &col); + // Initialize the 2d array + int **arr = malloc(sizeof(int *) * row); + for (int i = 0; i < row; i++) { + arr[i] = malloc(sizeof(int) * col); + } + + for (int i = 0; i < row; i++) { + for (int j = 0; j < col; j++) { + scanf("%d", &arr[i][j]); + } + } + + for (int i = 0; i < row; i++) { + for (int j = 0; j < col - 1; j++) { + printf("%d ", arr[i][j] * -10); + } + printf("%d\n", arr[i][col - 1] * -10); + } + + // Free the 2d array + for (int i = 0; i < row; i++) { + free(arr[i]); + } + free(arr); + return 0; +} diff --git a/semester1/pset13/2-3-ArrayEX.c b/semester1/pset13/2-3-ArrayEX.c new file mode 100644 index 0000000..58baa96 --- /dev/null +++ b/semester1/pset13/2-3-ArrayEX.c @@ -0,0 +1,50 @@ +#include +#include +#include +#define MAX 100001 + +void sort(char **arr, int n); +void swap(char **arr1, char **arr2); + +int main(void) { + int n; + scanf("%d", &n); + getchar(); + // 2d array + char **str = malloc(sizeof(char *) * n); + // Buffer array + char *buffer = malloc(sizeof(char) * MAX); + + for (int i = 0; i < n; i++) { + fgets(buffer, MAX, stdin); + str[i] = malloc(strlen(buffer) + 1); + strcpy(str[i], buffer); + } + + sort(str, n); + + for (int i = 0; i < n; i++) { + printf("%s", str[i]); + } + + // Free up memory + free(buffer); + for (int i = 0; i < n; i++) { + free(str[i]); + } + free(str); + return 0; +} + +void sort(char **arr, int n) { + for (int i = 0; i < n; i++) { + for (int j = 0; j < n - 1; j++) { + if (strcmp(arr[j], arr[j + 1]) > 0) { + // Why I can't use swap() here? + char *tmp = arr[j]; + arr[j] = arr[j + 1]; + arr[j + 1] = tmp; + } + } + } +} diff --git a/semester1/pset13/2-4-ArrayEX.c b/semester1/pset13/2-4-ArrayEX.c new file mode 120000 index 0000000..6104f4b --- /dev/null +++ b/semester1/pset13/2-4-ArrayEX.c @@ -0,0 +1 @@ +2-3-ArrayEX.c \ No newline at end of file