Having trouble detecting my mistake in my coding - c

I am still new to C programming and I am having a bit of a problem in my coding. I am aware that I can't just ask for help without trying to fix it by myself first, so I tried fixing it and is still having the same problem.
My problem is, my coding displayed an incorrect calculation like below.
ORDER PRICE SUMMARY
===========================================
Customer No. Total Order Price(RM)
===========================================
1 RM 40.00
2 RM 40.00
3 RM 478664371470163710000000000000000.00
===========================================
Grand Total RM 478664371470163710000000000000000.00
===========================================
Customer 1 and 2 showed the correct price but it just got messed up for Customer 3, which affects the grand total.
My coding is below, and it is obvious that I am using the simplest way of writing my code since my goal is to just answer a coding question.
#include <stdio.h>
float calculatePrice(char);
void main()
{
char comboType, addon;
int comboQty, addonQty,i=1,j=1;
float orderPrice = 0.00, comboPrice, addonPrice, grandPrice=0.00; // new float
float customerPayment[3], allPrice[3]; // declare array
printf ("--------------------------------------------------------------\n");
printf (" ~ SATAY RESTAURANT ~ \n");
printf ("--------------------------------------------------------------\n");
printf (" Combo Type Item Price (RM) \n");
printf ("--------------------------------------------------------------\n");
printf (" A 25 Chicken Stay + 25 Beef Satay 40.00\n");
printf (" B 30 Chicken Stay + 20 Mutton Satay 52.00\n");
printf (" C 10 Mutton Stay + 40 Beef Satay 46.00\n");
printf (" Add-On 1 Ketupat 0.60\n");
printf ("--------------------------------------------------------------\n");
for (j=0;j<3;j++)
{
printf("\n Customer %d\n",j+1);
printf("-------------");
printf("\n Enter Combo Type (A/B/C or X to end) : ");
scanf(" %c", &comboType);
while (comboType != 'X' && comboType != 'x') // start while loop
{
comboPrice = calculatePrice (comboType);
printf(" Order Price for Combo %c : RM%.2f \n ", comboType, comboPrice);
printf("\n Enter Combo Type (A/B/C or X to end) : ");
scanf(" %c", &comboType);
allPrice[j] += comboPrice;
}
printf("\n Add-On Ketupat (Y/N) : "); // if X, ask for add-on
scanf(" %c", &addon);
if (addon != 'N' && addon != 'n')
{
printf(" Enter Ketupat Quantity : ");
scanf("%d", &addonQty);
addonPrice = 0.60 * addonQty;
allPrice[j] += addonPrice;
printf(" Order price for Ketupat : RM%.2f\n",addonPrice);
}
printf("\n Total Order Price for Customer %d : RM%.2f\n\n",j+1, allPrice[j]);
customerPayment[j] = allPrice[j];
}
printf("\n\n\n\t ORDER PRICE SUMMARY ");
printf("\n===========================================");
printf("\n Customer No. Total Order Price(RM)");
printf("\n===========================================");
for (i = 0; i<3; i++)
{
printf("\n %d RM %.2f",i+1,customerPayment[i]);
grandPrice += customerPayment[i];
}
printf("\n===========================================");
printf("\n Grand Total RM %.2f",grandPrice);
printf("\n===========================================");
getch ();
}
float calculatePrice (char comboType)
{
float comboPrice, allPrice = 0.00;
int comboQty;
printf(" Enter Quantity : ");
scanf("%d", &comboQty);
if (comboType == 'A' || comboType == 'a')
{
comboPrice = 40.00 * comboQty;
}
if (comboType == 'B' || comboType == 'b')
{
comboPrice = 52.00 * comboQty;
}
if (comboType == 'C' || comboType == 'c')
{
comboPrice = 46.00 * comboQty;
}
return comboPrice;
}
It would be greatly appreciated if someone could help detecting my mistake.

At the beginning , you do not fill allPrice array with zeros, so you add to it what was left from memory.
Just at the start of your main, add allPrice[3] = {0, 0, 0}; and customerPayment[3] = {0, 0, 0};

Related

binary tree for sorting and search on c program

So i have a program to data the users input.
in this program i want to make some function
to ask the user for the product coming in
to display the history of data coming in by sorting by date.
to ask the user for the product coming out
to display the history of data coming out by sorting by date.
to search a specific product data by calling the code
to display all the data, the data is sorted by date and then the weight is data coming in minus data coming out
actually i have made a complete program of this, but the teacher updated the assignment. in the previous assignment i mostly use array instead of pointer and for sorting i use recursive bubble sort.
For now i need someone's help to make a sort by date using binary tree and search by product code using binary tree
Note : i must use binary tree because that's the assignment my teacher gave me
assignments are :
have a function with address argument
have a function with array argument
have function with argument as address to a structure
have a function with structure argument
add node to linked list/stack/queue/tree
read/delete node from linked list/stack/queue/tree.
Honestly i still understand linked list/stack/queue/tree. i thought to make a linked list i just change my array to a pointer
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
typedef struct {
int kode;
int amount;
char variety[20];
int weight;
int date;
}data;
data *innData;
data *outtData;
int menu;
int i;
int pointIn = 0, pointOut=0;
int amount = 0;
char variety[5][20] = {"Fish", "Crab", "Squid", "Clam", "Lobster"};
void sortDate(data *list, int range);
void back_menu();
void input();
void inputHistory();
void output();
void outHistory();
//void sort
//void calculateWeight
//void search();
//void showAll();
int main(){
innData=(data *)malloc(100*sizeof(data));
outtData=(data *)malloc(100*sizeof(data));
do {
printf(" ---------------- MARINE PRODUCT STOCK PROGRAM ---------------");
printf( " \n\nMAIN MENU :\n");
printf( "___________________________________________________________________\n\n");
printf( " 1. Input Product\n\n"); //data that the user input
printf( " 2. Entered History\n\n"); //show the history of the entered data by sorting the date
printf( " 3. Output Product\n\n"); //data that the user take out
printf( " 4. Exited Product\n\n");//show the history of the exited data by sorting the date
printf( " 5. Search Product\n\n"); //show the specific product by calling the code of the product
printf( " 6. Show All Product\n\n");
printf( " _____________________________\n\n");
printf( " choose (1 - 6) : ");
scanf ("%d", &menu);
if (menu < 1 || menu > 2) {
system("cls");
printf ("Please select the number between 1-2\n");
back_menu();
}
switch(menu) {
case 1:
input();
break;
case 2:
inputHistory();
break;
case 3:
output();
break;
case 4:
outHistory();
break;
// case 5:
// search(); // this function is used to search specific product by entering the code
// break;
// case 6:
// showAll(); // this function is used to show all of the stock in the warehouse. but the weight = input-output
// break;
}
free(innData);
free(outtData);
}
while (menu != 6);
system("cls");
printf ("============ Thankyou for using our program ============");
return 0;
}
void input(){
int code;
system ("cls");
printf("================= INPUT MENU =================\n\n");
printf("Enter the number of items to be recorded : "); scanf("%d", &amount);
printf( "_________________________________________________________________\n");
printf("\n Kode 0 = Fish \n kode 1 = Crab \n kode 2 = Squid \n kode 3 = Clam \n kode 4 = Lobster\n\t\t\t ");
for(i = 0; i < amount; i++){
printf("\n\nPRODUCT ORDER-%d",pointIn + 1);
printf("\n\tInput code\t : "); scanf(" %d", &code);
if(code < 0 || code > 4){
printf ("product with that number is not available, select number 0-4\n");
i--;
}
else {
strcpy( (innData+pointIn)->variety, variety[code]);
(innData+pointIn)->kode = code;
printf("\tvariety\t\t : %s\n", (innData+pointIn)->variety);
printf("\t Weight\t : "); scanf(" %d", &(innData+pointIn)->weight );
printf("\t Date (YYYYMMDD)\t : ");scanf(" %d", &(innData+pointIn)->date);
pointIn++;
}
}
back_menu();
}
void inputHistory(){
system("cls");
printf("***** INPUT STOCK DATE HISTORY ***** \n" );
printf("------------------------------------------------------------------\n");
printf("| DATE | CODE | NAME | WEIGHT | \n");
printf("------------------------------------------------------------------\n");
//call sort function here
for (i = 0; i < pointIn; i++){
printf(" %d %d %s %d \n", (innData+i)->date,(innData+i)->kode, (innData+i)->variety,(innData+i)->weight) ;
}
printf("------------------------------------------------------------------\n");
back_menu();
}
void output(){
int code;
system ("cls");
printf("================= INPUT MENU =================\n\n");
printf("Enter the number of items to be recorded : "); scanf("%d", &amount);
printf( "_________________________________________________________________\n");
printf("\n Kode 0 = Fish \n kode 1 = Crab \n kode 2 = Squid \n kode 3 = Clam \n kode 4 = Lobster\n\t\t\t ");
for(i = 0; i < amount; i++){
printf("\n\nPRODUCT ORDER-%d",pointOut + 1);
printf("\n\tInput code\t : "); scanf(" %d", &code);
if(code < 0 || code > 4){
printf ("product with that number is not available, select number 0-4\n");
i--;
}
else {
strcpy( (outtData+pointOut)->variety, variety[code]);
(outtData+pointOut)->kode = code;
printf("\tvariety\t\t : %s\n", (outtData+pointOut)->variety);
printf("\tWeight\t : "); scanf(" %d", &(outtData+pointOut)->weight );
printf("\tDate (YYYYMMDD)\t : ");scanf(" %d", &(outtData+pointOut)->date);
pointOut++;
}
}
back_menu();
}
void outHistory(){
system("cls");
printf("***** EXIT STOCK DATE HISTORY ***** \n" );
printf("------------------------------------------------------------------\n");
printf("| DATE | CODE | NAME | WEIGHT | \n");
printf("------------------------------------------------------------------\n");
//call sort function here
for (i = 0; i < pointIn; i++){
printf(" %d %d %s %d \n", (outtData+i)->date,(outtData+i)->kode, (outtData+i)->variety,(outtData+i)->weight) ;
}
printf("------------------------------------------------------------------\n");
back_menu();
}
void back_menu(){
printf("\n\n\t\t\tPress any key to continue.....");
getch();
system("cls");
}

error: ‘else’ without a previous ‘if’ but I think I have use a correct syntax

I'm new to C language and have been staring at my (probably abysmal) code for a while and can't figure out what's off about it.
Can anyone check my mistake :(
On compiler in said that error: ‘else’ without a previous ‘if’
else //[HIGHLIGHTED]
^~~~ , I have highlighted in comment [HIGHLIGHTED] the error lines to help you searching the line
#include <stdio.h>
#include <string.h>
void main()
{
int option;
option = 0;
while (option != 10)//For option purpose
{
char blood_type[5],next;// blood type purpose
char name[20];//name purpose
int count = 1;//turn on loop(True)
float discount, amountToBePaid, bill;
int amount;
int trial = 0, PIN, age;
float mass, generate;
printf("\n\n\t\t\t\tNational Blood Center x Tenaga Nasional Berhad Campaign");
printf("\n\n--------------------------------------------------------------------------------------------------------------------------");
printf("\n\t\t\t\tThank you for joining our campaign!");
printf("\n\t\t\t\tIf you donate :");
printf("\n\t\t\t\t ____________________________________ ");
printf("\n\t\t\t\t| Volume | Discount given |");
printf("\n\t\t\t\t ____________________________________");
printf("\n\t\t\t\t| 150 ml - 300 ml | 16 |");
printf("\n\t\t\t\t| 301 ml - 400 ml | 20 |");
printf("\n\t\t\t\t| 401 ml - higher | 25 |");
printf("\n\t\t\t\t ____________________________________");
printf("\n\n ! All contributor are advise to NOT donate your blood for over 470ml");
printf("\n\nDonator Condition:");
printf("\n1. Aged between 18 and 60 years old (for those less than 18, written consent from parents or legal guardian is required)");
printf("\n2. Body weight of at least 45 kg.");
printf("\n3. In good physical and mental health with no chronic medical illness.");
printf("\n4. Not on long term medications and has not been intoxicated by alcohol within 24 hours prior to donation.");
printf("\n\nDo you wish to continue?\n"); // this part ask user if they want to continue or not
printf("1.Yes\n");
printf("2.Cancel");
printf("\n\nEnter one of the above : "); //option, user are ask whether he/she wants to continue or not
scanf("%d", &option);
switch (option)// if the user wants to continue
{
case 1:
printf("Enter age:"); // security measurement, the user is ask to enter the his/her age/mass for confirmed that he/she fulfill all of the recuirment
scanf("%d", &age);
printf("Enter mass [in two decimal place]:");
scanf("%f", &mass);
if( age >=18 && age <=60)
if(mass > 60.00)
{
generate = age*mass; //a generated security code that derived from multiplication of age & mass (for increase the security measurement)
printf("Your code is %.2f", generate); //display generated code
}
else
{
printf("You may not fulfill all the conditions, try again later."); // if the user not fulfill all the conditions, the program will end
return ;
}
do
{
printf("\nInsert the generate code:");
scanf("%d", &PIN);
trial++;
}while (PIN != generate && trial != 3);
if (PIN == generate) //[HIGHLIGHTED]
printf("\nEnter your name: ");// next step to start the program
scanf("%s", name);
printf("\nPlease Enter Your Blood Type: ");
scanf("%s", blood_type);
printf("Please enter amount of your total blood donation (in ml) :");
scanf("%d", &amount);
printf("Enter your current electricity bill: Rm");
scanf("%f", &bill);
printf("\n");
printf("loading");//just a loading (no animation)
int value = 5;
while (value > 0)
{
printf(".");
value--;
}
while (count == 1 )
{
if ((strcmp(blood_type,"A")==0)||(strcmp(blood_type,"a")==0))
{
printf("\nYour Blood Type is %s", blood_type);
count = 0 ; //turn off loop (False)
}
else if((strcmp(blood_type,"B")==0)||(strcmp(blood_type,"b")==0))
{
printf("\nYour Blood Type is %s", blood_type);
count = 0 ; //turn off loop (False)
}
else if((strcmp(blood_type,"AB")==0)||(strcmp(blood_type,"ab")==0))
{
printf("\nYour Blood Type is %s", blood_type);
count = 0 ; //turn off loop (False)
}
else if((strcmp(blood_type,"o")==0)||(strcmp(blood_type,"O")==0))
{
printf("\nYour Blood Type is %s", blood_type);
count = 0 ; //turn off loop (False)
}
else
{
printf("\n-------------\n");
printf("Invalid input\n");
printf("-------------\n");
count = 0;//turn off loop (False)
main();
if(amount<150)
{
printf("\nYou have to paid: Rm%0.2f", bill);
printf("\nDonate for over 150 ml to enjoy a discount cut!");
}
else
{
if(amount>=150 && amount<=300)
{
discount = (bill*16)/100;
amountToBePaid = bill-discount;
printf("\nAfter applying the discount, you have to paid: Rm%0.2f", amountToBePaid);
}
else if(amount>300 && amount<=400)
{
discount = (bill*20)/100;
amountToBePaid = bill-discount;
printf("\nAfter applying the discount, you have to paid: Rm%0.2f", amountToBePaid);
}
else if(amount>400 && amount<600)
{
discount = (bill*25)/100;
amountToBePaid = bill-discount;
printf("\nAfter applying the discount, you have to paid: Rm%0.2f", amountToBePaid);
}
printf("\nThank you %s for your contribution!", name);
break;
else //[HIGHLIGHTED]
printf("\nSorry, Maximum attempt has been exceded. Please refer officer on duty." );
case 2:
return ;
default:
printf("Invalid input\n");
}
}
}
}
}
}
In this code:
else if(amount>400 && amount<600)
{
discount = (bill*25)/100;
amountToBePaid = bill-discount;
printf("\nAfter applying the discount, you have to paid: Rm%0.2f", amountToBePaid);
}
printf("\nThank you %s for your contribution!", name);
break;
else //[HIGHLIGHTED]
you have three statements after the if. The first is the compound statement from { to }. The second is the printf call, and the third is break;. However, in an if-else statement, if (expression) statement else statement, there can be only one statement after the if (expression) and before the else. To have multiple statements between them, you must enclose them in { and }, making a single compound statement.
It looks like you want that printf and break after all of the cases handling amounts less than 600 and want the else to handle amounts over 600. You cannot do that with the current structure you have. Instead, use a structure like this:
if (amount < 600)
{
// Write all the under-600 cases here, using `if` and `else if`.
// Execute a printf after all code for the under-600 cases.
printf("\nThank you %s for your contribution!", name);
}
else
{
// Handle the 600-or-over case here.
}
break;
I believe you're simply missing { } after the if, and else statements you have marked with
//[HIGHLIGHTED].

For loop cumulative calculation problem. C programming

Here I have created a compounding interest calculator. The user inputs principal, interest% and duration (in quarters). I have used a for loop for the initial calculation. But, I don't know how to get the total to rollover to the next quarter's principal.
Say the user inputs 1000, 5% and 2 quarters. The output should look like, Q1 Principal=$1000, Interest=0.05, Total=$1012.50, Q2 =$1012.50 =0.05 =$1025.16
Also my last Do while is giving me some issues. The ouput is spitting out a couple extra lines before letting the user start over.
Any advice would be greatly appreciated.
Thank you
#include <stdio.h>
int main (void)
{
int a = 0, b=0;
double interest, prin, total=0;
char check = ' ';
do{
do{
do{
printf (" Please enter principal:\n");
scanf ("%lf", &prin);
}while(prin <=0);
do{
printf ("Please enter desired interest greater
than 0 less than 20 :\n");
scanf ("%lf", &interest);
}while(interest <=0 || interest >20);
interest = interest/100;
do{
printf ("For how many quarters would you like
to deposit: (more than 0, less than 40) \n");
scanf ("%d", &b);
}while(b <=0 || b >40);
printf ("Is this information correct? Press X
to continue" );
scanf ("\n%c", &check);
}while(check != 'x' && check != 'X');
total = prin * (1+(interest *.25));
printf ("Quarter Principal Interest
Total\n");
for(a=1; ;++a){
printf ("%2d $%.2f %.2lf
$%.2lf\n", a, prin, interest, total);
if(a == b)
break;
}
printf ("Do you want to start over (Y/N)?");
scanf ("%c\n", &check);
}while(check != 'y' || check != 'Y');
return 0;
}
The are some problem with indentation and logic in your code. You need to updade principle in for loop statement. Then print it out .Here is my solution
#include <stdio.h>
int main(void)
{
int a = 0, b = 0;
double interest, prin, total = 0;
char check = ' ';
do {
do {
do {
printf(" Please enter principal:\n");
scanf("%lf", &prin);
} while (prin <= 0);
do {
printf("Please enter desired interest greater than 0 less than 20 :\n");
scanf("%lf", &interest);
} while (interest <= 0 || interest > 20);
interest = interest / 100;
do {
printf("For how many quarters would you like to deposit : (more than 0, less than 40) \n");
scanf("%d", &b);
} while (b <= 0 || b > 40);
printf("Is this information correct? Press X to continue" );
scanf("\n%c", &check);
} while (check != 'x' && check != 'X');
printf("Quarter Principal Interest Total\n");
for (a = 1; a<=b; ++a) {
total = prin * (1 + (interest *.25));
printf("%2d $%.2f %.2lf $%.2lf\n", a, prin, interest, total);
prin = total;
}
printf("Do you want to start over (Y/N)?");
scanf("%c\n", &check);
} while (check != 'y' || check != 'Y');
return 0;
}

How To get program to repeat when asked y or n

i am trying to get this program to repeat when prompted Y or N and i cant seem to get it to work right for some reason and this is the last thing i have left and im pretty sure the rest of the code is right i think all i need is it to repeat the whole program if the user enters a "Y" or just exits if the user enters "N"
int main(void)
{
// Constant and Variable Declarations
const int MPH_SPEED_MIN = 1;
const int MPH_SPEED_MAX = 100;
const int HOURS_TRAVLED_MIN = 1;
int mphSpeed = 1;
int hoursEntered = 0;
int distanceTraveled = 0;
int counterNum = 0;
int distanceNum = 0;
char ch = 'y';
// *** Input ***
do {
printf("What is the speed of the vehicle in MPH? ");
scanf("%d", &mphSpeed);
while ((mphSpeed < MPH_SPEED_MIN) || (mphSpeed > MPH_SPEED_MAX)) {
printf("\tThe speed entered must be between %d and %d inclusive
\n",MPH_SPEED_MIN, MPH_SPEED_MAX);
printf("\tPlease re-enter the speed of the vehicle in MPH: ");
scanf("%d", &mphSpeed);
}
printf("How many hours has it traveled? ");
scanf("%d", &hoursEntered);
while (hoursEntered < HOURS_TRAVLED_MIN) {
printf("\tThe hours traveled must be a positive number.\n");
printf("\tPlease re-enter the number of hours traveled: ");
scanf("%d", &hoursEntered);
}
printf("\n");
printf("Hour\tDistance Traveled\n");
distanceTraveled = hoursEntered * mphSpeed;
for (counterNum = 1; counterNum <= hoursEntered; counterNum++) {
distanceNum = distanceTraveled * counterNum;
printf("%d\t%d miles\n", counterNum, distanceNum);
}
printf("\n");
printf("Run the program again (Y/N)? ");
scanf("%c", &ch);
printf("\n");
} while (ch == 'Y' || ch == 'y');
; return 0;
When reading in with scanf(%c..., the statement very likely reads in a new line character left in the buffer from previous inputs. Read in a string instead, because %s ignores any leading white spaces (including such a new line character left in the buffer).
Try ...
char exitYN[2];
if (scanf("%1s",exitYN) != 1) {
exitYN[0]='N';
}
char ch = exitYN[0];
} while (ch == 'Y' || ch == 'y');
The one small yet, the most effective change that can be made here is adding a <space> before the %c while accepting the Y or N, i.e, scanf(" %c, &ch");
And I don't know if the following are errors while typing the code in StackOverflow, or are they originally errors in your code, but definitely are worth making changes:
Header file missing: #include<stdio.h>,
Unwanted and extra semicolon (;) before the return statement at the end,
missing closing bracket (}) at the end, after the return.
Here is the working code:
#include<stdio.h>
int main(void)
{
// Constant and Variable Declarations
const int MPH_SPEED_MIN = 1;
const int MPH_SPEED_MAX = 100;
const int HOURS_TRAVLED_MIN = 1;
int mphSpeed = 1;
int hoursEntered = 0;
int distanceTraveled = 0;
int counterNum = 0;
int distanceNum = 0;
char ch = 'y';
// *** Input ***
do {
printf("What is the speed of the vehicle in MPH? ");
scanf("%d", &mphSpeed);
while ((mphSpeed < MPH_SPEED_MIN) || (mphSpeed > MPH_SPEED_MAX)) {
printf("\tThe speed entered must be between %d and %d inclusive\n",MPH_SPEED_MIN, MPH_SPEED_MAX);
printf("\tPlease re-enter the speed of the vehicle in MPH: ");
scanf("%d", &mphSpeed);
}
printf("How many hours has it traveled? ");
scanf("%d", &hoursEntered);
while (hoursEntered < HOURS_TRAVLED_MIN) {
printf("\tThe hours traveled must be a positive number.\n");
printf("\tPlease re-enter the number of hours traveled: ");
scanf("%d", &hoursEntered);
}
printf("\n");
printf("Hour\tDistance Traveled\n");
distanceTraveled = hoursEntered * mphSpeed;
for (counterNum = 1; counterNum <= hoursEntered; counterNum++) {
distanceNum = distanceTraveled * counterNum;
printf("%d\t%d miles\n", counterNum, distanceNum);
}
printf("\n");
printf("Run the program again (Y/N)? ");
scanf(" %c", &ch);
printf("\n");
} while (ch == 'Y' || ch == 'y');
return 0;
}
I have also attached the output just in case you need to verify.
OUTPUT:
What is the speed of the vehicle in MPH? 12
How many hours has it traveled? 1
Hour Distance Traveled
1 12 miles
Run the program again (Y/N)? y
What is the speed of the vehicle in MPH? 6
How many hours has it traveled? 6
Hour Distance Traveled
1 36 miles
2 72 miles
3 108 miles
4 144 miles
5 180 miles
6 216 miles
Run the program again (Y/N)? n

C programming begginner issue

Ok so I'm trying to build a basic program to calculate the price of a pizza order. I want it to ask if the customer is done ordering. If they enter y then I want the loop to continue, if any other character entered I want it to stop. When I enter any character the program just continuously prints out all my printf statements. I am using codeblocks. Here is my code. I get 2 warnings.
warning: initialization makes integer from pointer without a cast [enabled by default] at line 17 where i declare the keepgoing variable.
warning: comparison between pointer and integer [enabled by default]|
at line 19 where the while loop starts.
#include <stdio.h>
#include <stdlib.h>
main()
{
#define LARGEPIZZAPRICE
#define SMALLPIZZAPRICE
#define LARGEPIZZATOPPING
#define SMALLPIZZATOPPING
#define DRINK
int numberOfLargePizzas;
int numberOfSmallPizzas;
int numberOfLargeToppings;
int numberOfSmallToppings;
int numberOfDrinks;
int keepGoing = "y";
while (keepGoing == "y")
{
printf("How many large pizza's do you want\n");
scanf(" %d", &numberOfLargePizzas);
printf("How many large toppings do you want\n");
scanf(" %d", &numberOfLargeToppings);
printf("How many small pizza's do you want\n");
scanf(" %d", &numberOfSmallPizzas);
printf("How many small toppings do you want\n");
scanf(" %d", &numberOfSmallToppings);
printf("Would you like to order more. Enter a y or n\n");
scanf(" %i", &keepGoing);
}
}`
*****UPDATE*****
Ok thanks for all the help, it's running good now. If somebody can look at it and give any tips to tighten it up or do what i'm doing easier, please let me know. This is learning experience for me and I'm doing it through trial and error. The program runs but I have a feeling I'm structuring it wrong. Here's what I have:
#include <stdio.h>
#include <stdlib.h>
main()
{
#define LARGEPIZZAPRICE 12
#define SMALLPIZZAPRICE 10
#define LARGEPIZZATOPPING 2
#define SMALLPIZZATOPPING 1.50
#define DRINK 1.50
#define TAXRATE .05
int numberOfLargePizzas;
int numberOfSmallPizzas;
int numberOfLargeToppings;
int numberOfSmallToppings;
int numberOfDrinks;
char keepGoing ='y';
float largePizzaTotal;
float smallPizzaTotal;
float drinkTotal;
while (keepGoing == 'y')
{
printf("How many large pizza's do you want\n");
scanf(" %d", &numberOfLargePizzas);
if(numberOfLargePizzas != 0){
printf("How many large toppings do you want\n");
scanf(" %d", &numberOfLargeToppings);
}
printf("How many small pizza's do you want\n");
scanf(" %d", &numberOfSmallPizzas);
if(numberOfSmallPizzas !=0){
printf("How many small toppings do you want\n");
scanf(" %d", &numberOfSmallToppings);
}
printf("How many drinks would you like\n");
scanf(" %int", &numberOfDrinks);
printf("Would you like to order more. Enter a y or n\n");
scanf(" %c", &keepGoing);
}
largePizzaTotal = (LARGEPIZZAPRICE*numberOfLargePizzas)+(LARGEPIZZATOPPING*numberOfLargeToppings);
smallPizzaTotal=(SMALLPIZZAPRICE*numberOfSmallPizzas)+(SMALLPIZZATOPPING*numberOfSmallToppings);
drinkTotal = DRINK*numberOfDrinks;
printf("Subtotal: %2f", largePizzaTotal + smallPizzaTotal + drinkTotal);
}
You can't compare strings that way in c, probably you meant
char keepGoing = 'y';
if (keepGoing == 'y')
but then you should fix the scanf() too
scanf(" %c", &keepGoing);
The
int keepGoing = "y";
compiles well if you have compiler warnings disabled, but it's wrong.
Your compiler is indeed telling you that it's wrong, because int and pointer are incompatible types.
You are comparing an integer variable with character data.
Replace int keepGoing = "y";
with
char keepGoing = 'y';
and replace
while (keepGoing == "y")
with while (keepGoing == 'y')
or if you want to take care of cases, replace it with
while ( keepGoing == 'y' || keepGoing == 'Y')
You asked for tips to tighten up what you are doing. I took a bit of time and outlined an approach to your pizza shop that surrounds a Pizza Shop Menu. Rather than prompting for how many of each -- during every loop, this just presents a small menu where you choose L for large, S for small and D for drink, and then fill in the quantity. (menu entries can be either upper or lower case) Invalid menu selections are not allowed (no error is shown, the menu just redisplays)
Rather than waiting to sum and total at the end, I find it easier to simply keep a running total of each type sold, the subtotal, tax, etc.. You can compare both methods and see which you prefer.
Also, after each scanf input (where the format string does not consume the newline), the input buffer is emptied to prevent scanf from appearing to skip over entries. Take a look and let me know if you have questions. There are many, many ways to do this, none more right than the next (as long as they are correct). It all comes down to format taste and efficiencies at that point. (note: no additional header files were included in case that is a limitation, so there are easier ways to check for a valid entry with strchr, etc.. using string.h, etc.)
#include <stdio.h>
#include <stdlib.h>
/* defines are preprocessor commands that simply cause the
* preprocessor to do a global search-and-replace of the
* labels with values. They traditionally go at the top.
* You can add storage type suffixes to the numbers to
* prevent ambiguity. (e.g. F float, U unsigned, ...)
*/
#define LARGEPIZZAPRICE 12.0F
#define SMALLPIZZAPRICE 10.0F
#define LARGEPIZZATOPPING 2.0F
#define SMALLPIZZATOPPING 1.50F
#define DRINK 1.50F
#define TAXRATE .05F
/* empty input buffer after reading from stdin */
void flush_stdin ()
{
int c = 0;
while ((c = getchar()) != '\n' && c != EOF);
}
int show_menu ()
{
int c = 0;
/* quick & dirty menu */
printf ("\n Pizza Shop Menu\n\n");
printf (" L) Large Pizza\n");
printf (" S) Small Pizza\n");
printf (" D) Drink\n");
printf (" --------------------\n");
printf (" C) Checkout\n\n");
printf (" Choice: ");
c = getchar ();
flush_stdin ();
/* return only upper case letters */
return c > 'Z' ? c - 'a' + 'A' : c;
}
int main (void)
{
/* ALWAYS INITIALIZE ALL VARIABLES
* accidentally reading from an uninitialized variable
* is Undefined Behavior.
*/
int numberOfLargePizzas = 0;
int numberOfSmallPizzas = 0;
int numberOfLargeToppings = 0;
int numberOfSmallToppings = 0;
int numberOfDrinks = 0;
float price = 0.0;
float subtotal = 0.0;
float tax = 0.0;
while (1)
{
int n = 0;
switch (show_menu())
{
case 'L' :
printf ("\n How many large pizza's do you want : ");
scanf ("%d", &n);
flush_stdin ();
if (n)
{
numberOfLargePizzas += n;
price = n * LARGEPIZZAPRICE;
tax += price * TAXRATE;
subtotal += price;
n = 0;
printf (" How many large toppings do you want: ");
scanf ("%d", &n);
flush_stdin ();
if (n)
{
numberOfLargeToppings += n;
price = n * LARGEPIZZATOPPING;
tax += price * TAXRATE;
subtotal += price;
}
}
printf ("\n Subtotal : %.2f\n Tax : %.2f\n Total : %.2f\n",
subtotal, tax, subtotal + tax);
break;
case 'S' :
printf ("\n How many small pizza's do you want : ");
scanf ("%d", &n);
flush_stdin ();
if (n)
{
numberOfSmallPizzas += n;
price = n * SMALLPIZZAPRICE;
tax += price * TAXRATE;
subtotal += price;
n = 0;
printf (" How many small toppings do you want: ");
scanf ("%d", &n);
flush_stdin ();
if (n)
{
numberOfSmallToppings += n;
price = n * SMALLPIZZATOPPING;
tax += price * TAXRATE;
subtotal += price;
}
}
printf ("\n Subtotal : %.2f\n Tax : %.2f\n Total : %.2f\n",
subtotal, tax, subtotal + tax);
break;
case 'D' :
printf ("\n How many drinks would you like: ");
scanf ("%d", &n);
flush_stdin ();
if (n)
{
numberOfDrinks += n;
price = n * DRINK;
tax += price * TAXRATE;
subtotal += price;
}
printf ("\n Subtotal : %.2f\n Tax : %.2f\n Total : %.2f\n",
subtotal, tax, subtotal + tax);
break;
case 'C' :
printf ("\nOrder:\n");
printf (" ------------------------\n");
printf (" Large Pizzas : %2d\n Large Toppings : %2d\n", numberOfLargePizzas, numberOfLargeToppings);
printf (" Small Pizzas : %2d\n Small Toppings : %2d\n", numberOfSmallPizzas, numberOfSmallToppings);
printf (" Drinks : %2d\n", numberOfDrinks );
printf (" ------------------------\n");
printf (" Subtotal : %6.2f\n Tax : %6.2f\n Total : %6.2f\n",
subtotal, tax, subtotal + tax);
printf (" ------------------------\n\n");
return 0;
default:
/* uncomment to show bad menu entry */
// printf (" <--invalid entry-->\n");
break;
}
}
return 0;
}
Example:
$ ./bin/pizzas
Pizza Shop Menu
L) Large Pizza
S) Small Pizza
D) Drink
--------------------
C) Checkout
Choice: l
How many large pizza's do you want : 2
How many large toppings do you want: 2
Subtotal : 28.00
Tax : 1.40
Total : 29.40
Pizza Shop Menu
L) Large Pizza
S) Small Pizza
D) Drink
--------------------
C) Checkout
Choice: d
How many drinks would you like: 4
Subtotal : 34.00
Tax : 1.70
Total : 35.70
Pizza Shop Menu
L) Large Pizza
S) Small Pizza
D) Drink
--------------------
C) Checkout
Choice: c
Order:
------------------------
Large Pizzas : 2
Large Toppings : 2
Small Pizzas : 0
Small Toppings : 0
Drinks : 4
------------------------
Subtotal : 34.00
Tax : 1.70
Total : 35.70
------------------------

Resources