Complementary task for topic: 8

M Nemeth · 2023-08-29 15:21:04.627218'

Dynamic arrays: Sum and average

Dynamic arrays: Sum and average

Create a C program that calculates the sum and average of elements in a dynamic integer array, the calculation should be in one separate function. The size and the elements of the array read from the user

Hint: Define a function calculateSumAndAverage that takes a pointer to the dynamic array, the size of the array, and two integer pointers to store the sum and average.
In the main function, ask the user to input the size of the array.
Allocate memory for the dynamic array based on the user input.
Ask the user to input the elements of the dynamic array.
Call the calculateSumAndAverage function, passing the dynamic array, size, and two integer pointers to store the sum and average.
Print the elements of the dynamic array, the sum, and the average.

Solution
#include 
#include 

void calculateSumAndAverage(int* arr, int size, int* sum, int* average) {
    *sum = 0;
    for (int i = 0; i < size; i++) {
        *sum += arr[i]; // Calculate the sum of elements
    }
    *average = *sum / size; // Calculate the average
}

int main() {
    int size, sum, average;

    printf("Enter the size of the array: ");
    scanf("%d", &size);

    int* dynamicArray = (int*)malloc(size * sizeof(int));

    printf("Enter the elements of the array:\n");
    for (int i = 0; i < size; i++) {
        printf("Element %d: ", i + 1);
        scanf("%d", &dynamicArray[i]);
    }

    calculateSumAndAverage(dynamicArray, size, &sum, &average);

    printf("\nArray Elements: ");
    for (int i = 0; i < size; i++) {
        printf("%d ", dynamicArray[i]);
    }

    printf("\nSum: %d\n", sum);
    printf("Average: %d\n", average);

    free(dynamicArray);

    return 0;
}



Explanation
n this task, we define a function calculateSumAndAverage that takes a pointer arr to the dynamic array, the size of the array, and two integer pointers sum and average.

Inside the calculateSumAndAverage function, we initialize sum to 0. Then, we use a for loop to traverse the dynamic array and calculate the sum of its elements.

After calculating the sum, we calculate the average by dividing the sum by the size of the array.

In the main function, we ask the user to input the size of the array and allocate memory for the dynamic array using malloc.

We ask the user to input the elements of the dynamic array using a for loop.

We call the calculateSumAndAverage function, passing the dynamic array, size, and two integer pointers to store the sum and average.

Finally, we print the elements of the dynamic array, the sum, and the average using printf.

Don't forget to free the dynamically allocated memory using free at the end of the program to avoid memory leaks.
< < previous    next > >