X

C Program to Find Largest Number Using Dynamic Memory Allocation

To understand this example, you should have the knowledge of the following C programming topics:


Find the Largest Element in a Dynamically Allocated Memory

#include #include 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.

Categories: Uncategorized
ilexjjtt-ca: