C Program to Calculating a floating-point average using pointers

C Program to Calculating a floating-point average using pointers



#include
#include
#include

int main(void)
{
double *values = NULL; /* Pointer to memory holding data values */
double *temp = NULL; /* Pointer to newly allocated memory */
double sum = 0.0; /* Sum of values */
int capacity = 0; /* Maximum number of values that can be stored */
int increment = 5; /* Capacity increment for dynamic allocation */
int count = 0; /* Number of values read */
char answer = 'n';

do
{
if(count == capacity) /* Check if there is spare memory */
{
capacity += increment; /* Increase the capacity of memory by increment */
temp = (double*)malloc((capacity)*sizeof(double)); /* and allocate it */
if(!temp) /* If memory was not allocated */
{ /* Output a message and end */
printf("Memory allocation failed. Terminating program.");
exit(1);
}
if(!values) /* Are there any values? */
values = temp; /* No - so just copy address of new memory */
else /* Yes - so copy data from old to new */
{
for(int i = 0 ; i<=count ; i++)
*(temp + i) = *(values + i);
free(values); /* Free the old memory */
values = temp; /* Copy address of new */
}
temp = NULL; /* Reset pointer */
}

printf("Enter a value: ");
scanf("%lf", values+count++);

printf("Do you want to enter another(y or n)? ");
scanf(" %c", &answer);
}while(tolower(answer) == 'y');

/* Now sum the values */
for(int i = 0 ; i<=count ; i++)
sum += *(values+i);

/* Output the average */
printf("\n The average of the the values you entered is %.2lf.\n", sum/count);
free(values); /* We are done - so free the memory */
return 0;
}




Related Links :

No comments:

Post a Comment


If you face any Problem in viewing code such as Incomplete "For Loops" or "Incorrect greater than or smaller" than equal to signs then please collect from My Web Site CLICK HERE


More Useful Topics...

 

History Of C..

In the beginning was Charles Babbage and his Analytical Engine, a machine
he built in 1822 that could be programmed to carry out different computations.
Move forward more than 100 years, where the U.S. government in
1942 used concepts from Babbage’s engine to create the ENIAC, the first
modern computer.
Meanwhile, over at the AT&T Bell Labs, in 1972 Dennis Ritchie was working
with two languages: B (for Bell) and BCPL (Basic Combined Programming
Language). Inspired by Pascal, Mr. Ritchie developed the C programming
language.

My 1st Program...


#include
#include
void main ()
{
clrscr ();
printf ("\n\n\n\n");
printf ("\t\t\t*******Pankaj *******\n");
printf ("\t\t\t********************************\n");
printf ("\t\t\t\"Life is Good...\"\n");
printf ("\t\t\t********************************");
getch ();
}

Next Step...


#include
#include

void main ()
{
clrscr ();
printf ("\n\n\n\n\n\n\n\n");
printf ("\t\t\t --------------------------- \n\n");

printf ("\t\t\t | IGCT, Info Computers, INDIA | \n\n");
printf ("\t\t\t --------------------------- ");

getch ();

}

Hits!!!