Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 21 additions & 19 deletions src/week4_1_dynamic_array.c
Original file line number Diff line number Diff line change
@@ -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 <stdio.h>
#include <stdlib.h>

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;
}