Find Largest Number Using Dynamic Memory Allocation in C

Exercise:

Write a C Program to find largest number using dynamic memory allocation.

Click Here to View the Solution!
#include <stdio.h>
#include <stdlib.h>
int main() {
    int num;
    float *data;
    printf("Enter the total number of elements: ");
    scanf("%d", &num);
    data = (float *)calloc(num, sizeof(float));

    if (data == NULL) {
        printf("Error!!! memory not allocated to given element.");
        exit(0);
    }
    for (int i = 0; i < num; ++i) {
        printf("Enter Number %d: ", i + 1);
        scanf("%f", data + i);
    }
    for (int i = 1; i < num; ++i) {
        if (*data < *(data + i)) {
            *data = *(data + i);
        }
    }
    printf("Largest number = %.2f", *data);
    return 0;
}
Click Here to View the Output!
Enter the total number of elements: 3
Enter Number 1: 5
Enter Number 2: 9
Enter Number 3: 2
Largest number = 9.00
Click Here to View the Explanation!
  • This program is used to determine the largest elements by using a dynamic memory allocation.
  • In main(), the program requests the user to enter the total number of elements and stores it in the variable num using the scanf() function.
  • The program will then allocate the memory for num elements which are set to be float numbers.
  • The calloc() function is used which allocates space in the memory for num number of elements of the type float.
  • The output of the calloc() function is stored in data with a condition that if the array data is already NULL before the memory allocation, an error message will be displayed.
  • The user is then requested to enter the numbers in the allocated memory of the array.
  • Finally, the largest number in the array and the allocated memory is found by iterating num number of times and each time comparing the elements of the array data.
  • The largest number is then printed.

%d bloggers like this: