C Example for Beginners: C Program to Find Largest Number Using Dynamic Memory Allocation

Hits: 462

(C programming Example for Beginners)

C Program to Find Largest Number Using Dynamic Memory Allocation

In this example, you will learn to find the largest number entered by the user in a dynamically allocated memory.


Find the Largest Element in a Dynamically Allocated Memory


#include <stdio.h>
#include <stdlib.h>
int main(){
    int num;
    float *data;
    printf("Enter the total number of elements: ");
    scanf("%d", &num);

    // Allocating memory for num elements
    data = (float *)calloc(num, sizeof(float));
    if (data == NULL) {
        printf("Error!!! memory not allocated.");
        exit(0);
    }

    // Storing numbers entered by the user.
    for (int i = 0; i < num; ++i) {
        printf("Enter Number %d: ", i + 1);
        scanf("%f", data + i);
    }

    // Finding the largest number
    for (int i = 1; i < num; ++i) {
        if (*data < *(data + i))
            *data = *(data + i);
    }
    printf("Largest number = %.2f", *data);

    return 0;
}

Output

Enter the total number of elements: 5
Enter Number 1: 3.4
Enter Number 2: 2.4
Enter Number 3: -5
Enter Number 4: 24.2
Enter Number 5: 6.7
Largest number = 24.20

In the program, the user is asked to enter the number of elements, which is stored in variable num. We will allocate memory for num number of float values.

Then, the user is asked to enter num numbers. These numbers are stored in the dynamically allocated memory.

Finally, the largest number among these numbers is determined and printed on the screen.

 

 

C Example for Beginners: C Program to Find Largest Number Using Dynamic Memory Allocation

Sign up to get end-to-end “Learn By Coding” example.



Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.