From 8889684a846c6de1f2b5d2e770a23aa5eca8d1f6 Mon Sep 17 00:00:00 2001 From: tahaunal7 Date: Sun, 12 Oct 2025 01:33:27 +0300 Subject: [PATCH] Added student info and completed week4_1_dynamic_array.c --- src/week4_1_dynamic_array.c | 40 +++++++++++++++++++------------------ 1 file changed, 21 insertions(+), 19 deletions(-) diff --git a/src/week4_1_dynamic_array.c b/src/week4_1_dynamic_array.c index 575567f..5b71796 100644 --- a/src/week4_1_dynamic_array.c +++ b/src/week4_1_dynamic_array.c @@ -1,38 +1,40 @@ /* * week4_1_dynamic_array.c - * Author: [Your Name] - * Student ID: [Your ID] + * Author: Mehmet Taha Ünal + * Student ID: 231AMB077 * Description: - * Demonstrates creation and usage of a dynamic array using malloc. - * Students should allocate memory for an integer array, fill it with data, - * compute something (e.g., average), and then free the memory. + * Demonstrates creation and usage of a dynamic array using malloc. + * Students allocate memory for integers, fill it with user input, + * compute the sum and average, and then free the memory properly. */ #include #include int main(void) { - int n; - int *arr = NULL; + int n, *arr, sum = 0; + double avg; printf("Enter number of elements: "); - if (scanf("%d", &n) != 1 || n <= 0) { - printf("Invalid size.\n"); + scanf("%d", &n); + + arr = (int *)malloc(n * sizeof(int)); + if (arr == NULL) { + printf("Memory allocation failed.\n"); return 1; } - // TODO: Allocate memory for n integers using malloc - // Example: arr = malloc(n * sizeof(int)); - - // TODO: Check allocation success - - // TODO: Read n integers from user input and store in array - - // TODO: Compute sum and average + printf("Enter %d integers: ", n); + for (int i = 0; i < n; i++) { + scanf("%d", &arr[i]); + sum += arr[i]; + } - // TODO: Print the results + avg = (double)sum / n; - // TODO: Free allocated memory + printf("Sum = %d\n", sum); + printf("Average = %.2f\n", avg); + free(arr); return 0; }