C Program to Find Largest Number Using Dynamic Memory Allocation
This tutorial will teach us how to locate the highest number a user has ever input into a dynamically allocated memory.
C Program:
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int no;
double *data_n;
printf ( "Put the total number of elements: " );
scanf ( "%d", & no );
// Memory allocation for required items
data_n = ( double * ) calloc ( no, sizeof ( double ) );
if ( data_n == NULL )
{
printf ( "Invalid." );
exit ( 0 );
}
// keeping the user's inputted digits.
for ( int p = 0; p < no; ++ p )
{
printf ( "Put number %d: ", p + 1 );
scanf ( "%lf", data_n + p );
}
// computing the maximum number
for ( int p = 1; p < no; ++ p )
{
if ( *data_n < *( data_n + p ) )
{
*data_n = *( data_n + p );
}
}
printf ( "The largest number is %.2lf", *data_n );
free ( data_n );
return 0;
}
Output:
Put the total number of elements: 3
Put number 1: 45
Put number 2: 93
Put number 3: 61
The largest number is 93.00