C Program to Find Largest Number Using Dynamic Memory Allocation using - C calloc & C pointers
ADVERTISEMENTS
C Program to Find Largest Number Using Dynamic Memory Allocation using - C calloc & C Pointers.
Example
Enter the element counts: 4
INPUT-[1]: 10
INPUT-[2]: 20
INPUT-[3]: 50
INPUT-[4]: 15
Largest Number: 50.00
INPUT-[1]: 10
INPUT-[2]: 20
INPUT-[3]: 50
INPUT-[4]: 15
Largest Number: 50.00
You should know about the following topics in C programming to understand this program:
- C Pointers
- C calloc method
- Dynamic Memory Allocation in C
Source
// C Program to Find Largest Number Using Dynamic Memory Allocation
#include <stdio.h>
#include <stdlib.h>
// It's the main function of the program
int main() {
int count;
double *data_container;
// Step-1 Take input from the user
printf("Enter the element counts: ");
scanf("%d", &count);
// Step-2 Allocate the memory to Nth elements
data_container = (double *)calloc(count, sizeof(double));
if (data_container == NULL) {
printf("Memory allocation failed!");
exit(0);
}
// Step-3 Take input of Nth elements by the user and store into 'data_container'
for (int i = 0; i < count; i++) {
printf("INPUT-[%d]: ", i + 1);
scanf("%lf", data_container + i);
}
// Step-4 Find the largest number from 'data_container'
for (int i = 0; i < count; i++) {
if (*data_container < *(data_container + i)) {
*data_container = *(data_container + i);
}
}
// Step-5 Print the largest number output of the program
printf("Largest Number: %.2lf\n", *data_container);
// Step-6 Release 'data_container' from Allocated Memory
free(data_container);
return 0;
}
Output
Enter the element counts: 10
INPUT-[1]: 4
INPUT-[2]: 8
INPUT-[3]: 10
INPUT-[4]: 25
INPUT-[5]: 90
INPUT-[6]: 34
INPUT-[7]: 67
INPUT-[8]: 20
INPUT-[9]: 5
INPUT-[10]: 80
Largest Number: 90.00