Making the Density Example a Subprogram

NOTE: the only changes made to the original main is to add the function prototype for density_calcs() and to change the header from int main(void) to void density_calc(void) and to remove the return (0) from the new function.


#include <stdio.h>

/* function prototypes - void functions correspond to the concept of 
                         procedures */

void get_int_low(int *, int);  /* void get_int_low(int *val, int low); */
int calc_volume_cube(int);     /* int calc_volumne_cube(int side); */
float calc_density(int, int);  /* int calc_density(int vol, int mass); */
void density_calcs(void);

/* function header for density of a cube goes here */

void density_calcs(void)
{
  int side, mass, volume; 
  float density;

  printf("\n\n\nEnter the length of a side in centimeters ");
  get_int_low(&side, 1);
  printf("\nEnter the mass of the cube in grams ");
  get_int_low(&mass, 1);
  volume = calc_volume_cube(side); 
  density = calc_density(volume, mass);
  printf("\nFor a cube with side = %d and mass = %d, the density is %f\n",
                side, mass, density);
  printf("\n\n\n");
}


/** function header goes here **/
void get_int_low(int *val, int low)
{
   do
   {
     scanf("%d", val);
     if (*val < low)
       printf("\nError in input, value must be >= %d - try again. ", low);
   }
   while (*val < low);
}

 
/** function header goes here **/
int calc_volume_cube(int side)
{
   return(side * side * side);
}


/** function header goes here **/
float calc_density(int vol, int mass)
{
   return ((float)mass/(float)vol);

}