Sunday, September 14, 2014

write a program to calculate sum and average by allocating dynamic memory (malloc function)


Problem

Write a program that asks the user to input marks of some subjects. The program calculates sum and average of those marks and prints them on screen. As a programmer you are not sure that a user wants to input marks of how many subjects. So, your program first asks the user for how many subject you want to input marks. The program allocates dynamic memory using malloc function.
Prototype of malloc function is:
void* malloc (int n);

where n is the number of bytes to be allocated you have to type cast void* pointer to int* since you know that you will be storing int values in that allocated memory.

Note: Use free function when the program ends.

Solution - Code

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include <string.h>
int main ()
{
 int sum=0, avg, i;
 int how_many;
 int *p;

 printf ("Enter number of subjects whose marks you want to input: ");
 scanf ("%d",&how_many);

 p = (int *)malloc(how_many * 4);

 if (p == NULL)
 {
  printf(" Out of memory!\n");
  printf ("Press any key to close.");
  exit(0);
 }

 for (i=0;i<how_many;i++)
 {
  printf ("Enter marks of %dth subject: ",i+1);
  scanf ("%d",&p[i]);

  sum = (sum + p[i]);
 }

 avg = (sum / how_many);

 printf ("Sum = %d\n\n",sum);
 printf ("Average = %d\n\n",avg);

 free (p);

 printf ("press any key to close.");
 getch();
}

Sample Output


calculate sum & average using malloc function

No comments :

Post a Comment

Note: Only a member of this blog may post a comment.

Copyright 2017. All Rights Reserved. Privacy Policy / Terms And Conditions / Sitemap / Contact