Loops through all the numbers in array and figures out the smallest, the biggest, and the average. It then frees the memory. - C Memory

C examples for Memory:malloc

Description

Loops through all the numbers in array and figures out the smallest, the biggest, and the average. It then frees the memory.

Demo Code

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

int main()/*from  w w w .ja  v  a 2s. c  o  m*/
{
    int aSize = 200;
    int * randomNums;
    time_t t;
    double total = 0;
    int biggest, smallest;
    float average;

    srand(time(&t));

    randomNums = (int *) malloc(aSize * sizeof(int));
    // ensure that the array allocated properly
    if (!randomNums) {
        printf("Random array allocation failed!\n");
        exit(1);
    }
    // Loops through the array and assigns a random number between 1 and 500 to each element
    for (int i = 0; i < aSize; i++){
        randomNums[i] = (rand() % 500) + 1;
    }
    // Initialize the biggest and smallest number for comparison's sake
    biggest = 0;
    smallest = 500;

    for (int i = 0; i < aSize; i++){
        total += randomNums[i];
        if (randomNums[i] > biggest) {
            biggest = randomNums[i];
        }
        if (randomNums[i] < smallest) {
            smallest = randomNums[i];
        }
    }

    average = ((float)total)/((float)aSize);

    printf("The biggest random number is %d.\n", biggest);
    printf("The smallest random number is %d.\n", smallest);
    printf("The average of the random numbers is %.2f.\n", average);

    free(randomNums);
    return(0);
}

Result


Related Tutorials