Thread: A little help on this (C programming)

1. A little help on this (C programming)

I'm getting this error when calculating the total bill.

I kinda know what is the issue, it means if an user does not select one of the options, the value of that said "tp" would be undefined because the user did not select any quantity.

Problem is, i do not know how to fix this. How do i make it so that "tp1,2,3,4" will be defined no matter if the user chooses it or not?

Code:
```
#include <stdio.h>

int main(void) {
int quantity1, quantity2, quantity3, quantity4;
double tp1, tp2, tp3, tp4;

printf("\n\n    Product Code        Price(USD)  \n");
printf("        [1]              20.20     \n");
printf("        [2]              14.50     \n");
printf("        [3]              5.45      \n");
printf("        [4]              2.80      \n");
printf("Enter the product code you wish to purchase : ");
scanf("%d", &choice);
switch (choice)
{
case 1:

{
printf("You have selected product code 1.");
scanf("%d", &quantity1);

tp1 = quantity1 * 20.20;

}
break;

case 2:
{
printf("You have selected product code 2.");
scanf("%d", &quantity2);

tp2 = quantity2 * 14.50;

}
break;

case 3:
{
printf("You have selected product code 3.");
scanf("%d", &quantity3);

tp3 = quantity3 * 5.45;
}
break;

case 4:
{
printf("You have selected product code 4.");
scanf("%d", &quantity4);

tp4 = quantity4 * 2.80;

}
break;

default:
{
printf("\nInvalid Choice");
break;
}

}

double totalbill;
totalbill = tp1 + tp2 + tp3 + tp4;
printf("totalbill = %.2f", totalbill);

return 0;
}```

2. I guess you could use an assignment.

double tp1 = 0, tp2 = 0, tp3 = 0, tp4 = 0;

3. Just having a quick look, I can't see where you declare "choice".

Just adding on to what Salem has said, at the end of your switch statement you have the following code...
Code:
`totalbill = tp1 + tp2 + tp3 + tp4;`
If the user has endered choice 1 for the switch statement, tp1 gets a value but tp2..4 haven't got a value yet.

4. any idea how i can accumulate the data (storing it) as i want it so if an user have the option to add on their items, the total price would change accordingly to what the user added on

5. It looks like all you'd need to do is add a loop around your switch statement.

The normal thing in this sort of set up is a do/while loop - i.e. Do while user input isn't a certain number. You tell the user what number that is in the menu.

You are extremely close - Give it a go and see if you can get it