C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Dynamic Memory Allocation in C

Average of dynamic array

C Program: Average of dynamic array

C

#include <stdio.h>

#include <stdlib.h>

 

int main() {

    int *arr;

    int n, i;

    float sum = 0, avg;

 

    // Step 1: Get array size

    printf("Enter number of elements: ");

    scanf("%d", &n);

 

    // Step 2: Dynamically allocate memory

    arr = (int*) malloc(n * sizeof(int));

 

    if (arr == NULL) {

        printf("Memory allocation failed!\n");

        return 1;

    }

 

    // Step 3: Input array elements

    printf("\nEnter %d elements:\n", n);

    for (i = 0; i < n; i++) {

        printf("Element %d: ", i + 1);

        scanf("%d", &arr[i]);

        sum += arr[i];

    }

 

    // Step 4: Calculate average

    avg = sum / n;

 

    // Step 5: Display result

    printf("\nAverage of array elements = %.2f\n", avg);

 

    // Step 6: Free allocated memory

    free(arr);

 

    return 0;

}

Output

 
OUTPUT :
Enter number of elements: 5
Enter 5 elements:
Element 1: 10
Element 2: 20
Element 3: 30
Element 4: 40
Element 5: 50

Average of array elements = 30.00


Explanation

Step

Description

malloc()

Allocates memory dynamically based on user input.

sum += arr[i]

Accumulates the total of all elements.

avg = sum / n

Computes the average value.

free(arr)

Frees allocated memory to prevent leaks.