I was bored.
Code:
#include <stdio.h>
#include <stdlib.h>
#define CITY_COUNT 2
#define SHOP_COUNT_PER_CITY 3
static const char * const products[] =
{
"Nothing", "Beer", "Diapers", "Bread"
};
static const int product_prices[] = { 0, 10, 5, 2 };
static const double tax_rate = 0.18;
static void display_shop_and_city(int shop, int city)
{
printf("You are at City # %d and Shop # %d\n", city, shop);
}
static void display_options()
{
int i = 1;
for (; i < sizeof(*products) ; ++i)
{
printf("%d --> %s\n", i, products[i]);
}
printf("%d --> %s\n", 0, products[0]);
}
static int get_input(int shop, int city)
{
int selected_item = 0;
do
{
display_shop_and_city(shop, city);
display_options();
scanf("%d", &selected_item);
}
while (selected_item < 0 || selected_item > sizeof(*products));
if (0 == selected_item)
{
printf("Nothing purchased\n");
}
return selected_item;
}
static void print_purchased_items(int *purchased_items)
{
int i = 0;
for (; i < sizeof(*products); ++i)
{
printf ("%s: %d\n", products[i], purchased_items[i]);
}
}
static int get_subtotal(int *purchased_items)
{
int i = 0, subtotal = 0;
for (i = 0 ; i < sizeof(*products) ; ++i)
{
subtotal += (purchased_items[i] * product_prices[i]);
}
return subtotal;
}
static double calculate_tax(int subtotal)
{
return subtotal * tax_rate;
}
int main()
{
int selected_item = 0;
int shop = 0, city = 0;
int *items_purchased = calloc (sizeof(*products),
sizeof(*items_purchased));
while (++city <= CITY_COUNT)
{
while (++shop <= SHOP_COUNT_PER_CITY)
{
selected_item = get_input(shop, city);
++items_purchased[selected_item];
}
shop = 0;
}
printf ("\n");
print_purchased_items(items_purchased);
printf("\n");
int subtotal = get_subtotal(items_purchased);
free (items_purchased);
printf("Subtotal: $%.2f\n", (double)subtotal);
double tax = calculate_tax(subtotal);
printf("Tax: $%.2f\n", tax);
printf("Total: $%.2f\n", subtotal + tax);
return 0;
}