How does a C program to find largest number using dynamic memory allocation work?
Courtesy: Programiz.com
In the program, we have asked the user to enter the total number of elements which is stored in the variable n
. Then, we have allocated memory for n number of double
values.
// Allocating memory for n double values
data = (double *)calloc(n, sizeof(double));
Then, we used a for
loop to take n number of data from the user.
// Storing elements
for (int i = 0; i < n; ++i) {
printf("Enter Number%d: ", i + 1);
scanf("%lf", data + i);
}
Finally, we used another for
loop to compute the largest number.
// Computing the largest number
for (int i = 1; i < n; ++i) {
if (*data < *(data + i))
*data = *(data + i);
}
}
Note: Instead of calloc()
, it's also possible to solve this problem using the malloc() function.
Comments
Post a Comment