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
66 changes: 41 additions & 25 deletions src/week4_1_dynamic_array.c
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/*
* week4_1_dynamic_array.c
* Author: [Your Name]
* Student ID: [Your ID]
* Author: [Mina Senturk]
* Student ID: [231ADB258]
* Description:
* Demonstrates creation and usage of a dynamic array using malloc.
* Students should allocate memory for an integer array, fill it with data,
Expand All @@ -12,27 +12,43 @@
#include <stdlib.h>

int main(void) {
int n;
int *arr = NULL;

printf("Enter number of elements: ");
if (scanf("%d", &n) != 1 || n <= 0) {
printf("Invalid size.\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

// TODO: Print the results

// TODO: Free allocated memory

return 0;
int n;
int *arr = NULL;

printf("Enter number of elements: ");
if (scanf("%d", &n) != 1 || n <= 0) {
printf("Invalid size.\n");
return 1;
}

// TODO: Allocate memory for n integers using malloc
// Example: arr = malloc(n * sizeof(int));
arr = malloc(n * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed.\n");
return 1;
}

// TODO: Read n integers from user input and store in array
printf("Enter %d integers: ", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

// TODO: Compute sum and average
int sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}

double average = (double)sum / n;

// TODO: Print the results
printf("Sum = %d\n", sum);
printf("Average = %.2f\n", average);

// TODO: Free allocated memory
free(arr);

return 0;
}