2.15. Example of developing a C program

2.15.1. Specification

Develop a program that cheap and hungry college students can use to find the cheapest pizza in town. The user will enter size of the pizza’s diameter in inches and the price in dollars. The program should report the price per square inch of pizza.

2.15.2. Design

Prompt the user for the size and price of the pizza. Validate that the supplied data makes sense. Then calculate the area of the pizza using the equation …

Area = \pi \times r^{2} = \pi \times \left(\frac{d}{2}\right)^{2}
= \pi \times \frac{d^{2}}{4}

Then just divide price by the area.

2.15.3. Coding

/*
 *  Calculate the area of a pizza and it's price per square inch.
 *
 *  Area = pi*diameter*diameter/4
 *  price per sq. inch = price / Area
 */

#include <stdio.h>
#define PI 3.1415927

int main(void)
{
   float diameter, price;
   float area;

   /*
    *  Prompt for and read pizza size
   */
   diameter = 0.0;
   while( diameter <= 0.0 ) {
      printf( "Enter diameter of the pizza in inches: ");
      scanf( "%f", &diameter);
      if (diameter <= 0.0)
         printf( "\nI'm still hungry, a pizza has a positive diameter.\n");
   }

   /*
    *  Prompt for and read pizza price
   */
   price = 0.0;
   while( price <= 0.0 ) {
      printf( "Enter the price of the pizza in dollars: ");
      scanf( "%f", &price);
      if( price <= 0.0 )  {
         printf( "\nIt must cost some thing.\n" );
         printf( "Enter a positive price please.\n" );
      }
   }
   /*
    * calculate and display results
   */
   area = diameter*diameter*PI/4;
   printf( "Size of pizza: %-5.3f sq inches.\n", area );

   printf( "Price per square inch: $%-5.2f\n", price/area );
   return(0);
}

2.15.4. Testing

1020 pilgrim:~> gcc pizza.c
1021 pilgrim:~> ./a.out
Enter diameter of the pizza in inches: 10
Enter the price of the pizza in dollars: 8.99
Size of pizza: 78.540 sq inches.
Price per square inch: $0.11

1022 pilgrim:~> ./a.out
Enter diameter of the pizza in inches: -2

I'm still hungry, a pizza has a positive diameter.
Enter diameter of the pizza in inches: 3
Enter the price of the pizza in dollars: 10
Size of pizza: 7.069 sq inches.
Price per square inch: $1.41