Skip to main content

Cost of Tea

Consider the problem of determining the cost of a bubble tea. Bubble tea is a drink that is made of a tea and a number of optional toppings. For our program, we will only have two toppings; tapioca and jelly. The base drink is 4.00 for a small size, 5.50 for a large size. Adding tapioca costs 0.75 more. Adding jelly costs 0.50 more.

How would we solve this problem?... Write down the steps that you would need to perform in English, then reveal for the answer.

Click to see steps
  • Ask user if they want a small or large size
  • Ask user if they wish to add tapioca
  • Ask user if they wish to add jelly
  • Determine drink price
  • Output Result

Here is a sample run:

Would you like a Large(L) or Small(S) drink? S
Would you like to add tapioca (Y or N)? Y
Would you like to add jelly (Y or N)? N
Price is: $6.25

In this situation, there are multiple pathways for each of our choices, however the choices are not mutually exclusive. Each of our options are independent. Choosing small or large does not exclude tapioca or include it automatically. Adding tapioca doesn't mean you can't add jelly. Thus, our constructs are different and the flow of our program is also very different.

Final program:

Putting all this together:

#include <stdio.h>
char getSize();
char getJelly();
char getTapioca();
double calculateTea(char size, char addTapioca, char addJelly);
void printResult(double price);

int main(void)
{
char size = getSize();
char addTapioca = getTapioca();
char addJelly = getJelly();
double price = calculateTea(size, addTapioca, addJelly);
printResult(price);
}

char getSize()
{
char size;
printf("Would you like a Large(L) or Small(S) drink? ");
//notice the space in front of the %c in this scanf().
//when you read a number, the compiler knows to ignore whitespace characters
//such as space, tab and newlines. However, when you read a character,
//space, tab and newlines may actually be the data you are trying to read.
//thus, the space in front of the %c means remove all leading whitepaces.
//this is especially important on the second and third scanfs that involve
//characters because when the user will type L then hit the return key (a newline)
//the newline must be "read" in order to get to the next piece of real information
scanf(" %c", &size);
return size;
}
char getTapioca()
{
char tapioca;
printf("Would you like to add tapioca (Y or N)? ");
scanf(" %c", &tapioca);
return tapioca;
}
char getJelly()
{
char jelly;
printf("Would you like to add jelly (Y or N)? ");
scanf(" %c", &jelly);
return jelly;
}
double calculateTea(char size, char addTapioca, char addJelly)
{
//default to small size price
double totalPrice = 4.00;
if(size == 'L'){
//change initial price if it is large
totalPrice = 5.50;
}
if(addTapioca=='Y'){
totalPrice += 0.75;
}
if(addJelly == 'N'){
totalPrice += 0.5;
}
return totalPrice;
}

void printResult(double price)
{
printf("Price is: $%.2lf\n",price);
}