C - Write program to calculate price based on quantity

Requirements

Calculate the price for a quantity entered by user.

The unit price is $5 and there is a discount of 10 percent for quantities over 30 and a 15 percent discount for quantities over 50.

Hint

Use if statement to check quantity.

Demo

#include <stdio.h>

int main(void)
{
  const int level1 = 30;               // Quantity over this level are at discount1
  const int level2 = 50;               // Quantity over this level are at discount2
  const double discount1 = 0.10;       // 10% discount
  const double discount2 = 0.15;       // 15% discount
  const double unit_price = 5.0;       // Basic unit price
  int quantity = 0;
  int total = 0;              // 0 to 30 at full price
  int a1 = 0;                  // 31 to 50 at level1 price
  int a2 = 0;                  // Over 50 at level2 price

  printf("Enter the quantity that you require: ");
  scanf("%d", &quantity);

  if (quantity > 50)                     // Quantity over 50
  {/* ww w. j  a va  2  s  . co m*/
    total = level1;
    a1 = level2 - level1;
    a2 = quantity - level2;
  }
  else if (quantity > 30)                // Quantity is from 30 to 50
  {
    total = level1;
    a1 = quantity - level1;
  }
  else
    total = quantity;

  printf("The total price for %d items is $%.2lf\n", quantity,
    unit_price*(total + (1.0 - discount1)*a1 + (1.0 - discount2)*a2));
  return 0;
}

Result

Related Quiz