1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
|
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
// Numbers: ...... Contains the allocated resources.
// BiggestNum: ... Holds the biggest number within 'Numbers'.
// InputBuffer: .. Contains the value given by the user.
// Total: ........ Contains the total of all numbers within 'Numbers'.
// I: ............ Used within the 'for' loop as the counter.
// Average: ...... Holds the average of 'Total'.
int *Numbers = NULL, BiggestNum = 0;
int InputBuffer = 0;
long Total = 0;
int I = 0;
float Average = 0.0f;
// Request the user input.
do
{
// Inform the user to input a value (make sure they know what the value
// they're entering is for). If the given value is less than or equal
// to zero, or, greater than 80, make then enter another number.
// Otherwise, break from the loop.
printf( "Please Enter How Many Number You Want to Add(1~80): " );
scanf( "%d", &InputBuffer );
} while( ( InputBuffer < 1 ) || ( InputBuffer > 80 ) );
// Dynamically create the array based on the user input (InputBuffer).
Numbers = ( ( int * )calloc( InputBuffer, sizeof( int ) ) );
if( Numbers == NULL )
{
// The allocation of 'Numbers' failed. Inform the user that the program
// will end.
printf( "Failed to allocate the array. Exiting" );
getchar( );
return 1;
}
// Here, we'll enter a loop which will perform 'n' passes. The amount of
// passes is determined by the value within 'InputBuffer'.
for( I = 0; I < InputBuffer; I++ )
{
// We'll use 'BiggestNum' here for two reasons:
// 1) To save stack space.
// 2) 'BiggestNum' isn't used until later on.
do
{
printf( "Enter number[%d]: ", ( I + 1 ) );
scanf( "%d", &BiggestNum );
} while( BiggestNum < 0 );
Numbers[I] = BiggestNum;
}
// Clear 'BiggestNum' from the last operation.
BiggestNum = 0;
// Here, we'll find the biggest number and store it within 'BiggestNum'.
for( I = 0; I < InputBuffer; I++ )
if( BiggestNum < Numbers[I] )
BiggestNum = Numbers[I];
// We'll enter another loop here. This time, we'll add up all if the numbers
// within 'Numbers'. The result of the computation will be stored within the
// previously defined variable, 'Total'.
for( I = 0; I < InputBuffer; I++ )
Total += Numbers[I];
// Compute the average.
Average = ( Total / 2.0f );
// Release the allocated memory. If we don't, we'll have leaking memory.
free( Numbers );
// Print the value stored within 'Total'.
printf( "\nSum of the numbers entered is: %d\n", Total );
// Print the average of 'Total'.
printf( "Average: %f\n", Average );
scanf( "%*d", NULL );
return 0;
}
|