Menu
Coddy logo textTech

Recap: Dynamic Array

Part of the Logic & Flow section of Coddy's C journey — lesson 37 of 63.

challenge icon

Challenge

Easy

Write a C program that creates a dynamic array based on user input, processes the data, and demonstrates proper memory management. Your program should:

  1. Read an integer n from the user representing the number of elements to store
  2. Use malloc() with sizeof() to dynamically allocate memory for an array of n integers
  3. Check if the memory allocation was successful - if it fails, print Memory allocation failed! and terminate the program
  4. If allocation succeeds, print Array of size [n] created successfully!
  5. Read n integer values from the user and store them in the allocated array
  6. Calculate and print the sum of all elements in the format: Sum: [value]
  7. Find and print the minimum value in the format: Minimum: [value]
  8. Count how many elements are greater than the average and print in the format: Elements above average: [count]
  9. Print the total memory used in bytes in the format: Memory used: [bytes] bytes
  10. Use free() to deallocate the memory
  11. Print Memory successfully freed! to confirm proper cleanup

Remember to include the <stdlib.h> header to use malloc() and free(). This challenge tests your complete understanding of dynamic memory management, from allocation through usage to proper cleanup.

For example, if the input is:

5
12 8 15 3 20

Your output should be:

Array of size 5 created successfully!
Sum: 58
Minimum: 3
Elements above average: 2
Memory used: 20 bytes
Memory successfully freed!

This comprehensive challenge demonstrates the complete lifecycle of dynamic memory management while performing meaningful data processing operations on the allocated array.

Try it yourself

#include <stdio.h>
#include <stdlib.h>

int main() {
    // Read the number of elements
    int n;
    scanf("%d", &n);
    
    // TODO: Write your code below
    // 1. Allocate memory for n integers using malloc()
    // 2. Check if allocation was successful
    // 3. Read n integers into the array
    // 4. Calculate sum, find minimum, count elements above average
    // 5. Print results and free memory
    
    return 0;
}

All lessons in Logic & Flow