Link to home
Start Free TrialLog in
Avatar of kinjal shah
kinjal shah

asked on

restaurant menu print billing system

The code snippet below is part of the restaurant menu program you previously used in the lab. Add a choice for a drink. Add the necessary code to allow the program to calculate the total price of order for the user. Assume the following price list:

Hamburger $5
Hotdog $4
Fries $3
Drink $2

The program should allow the user to keep entering order until choosing to exit. At the end the program prints an order summary similar to this:

You ordered 2 hamburger(s), 1 hotdog(s), 3 fries, 0 drink(s).

Price: $23
HST:  $2.99
Total: $25.99

=================================
Code snippet
===============================
do {

printf("What do you want to eat today?\n");
printf("1. Hamburger\n");
printf("2. Hotdog\n");
printf("3. Fries\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch(choice) {
case 1:
printf("You ordered a hamburger\n");
break;
case 2:
printf("You ordered a hotdog\n");
break;
case 3:
printf("You ordered fries\n");
break;
case 4:
printf("Order finished, thank you!\n");
break;
default:
printf("Wrong choice! try again: ");
}

} while (choice != 4)

Open in new window


needhelp in these ASAP
Avatar of Subrat (C++ windows/Linux)
Subrat (C++ windows/Linux)
Flag of India image

You can declare 3 variables representing no of each items. In each entry of choice, you can increment the variable. Once exiting the loop you can calculate  and display the desired output.

More over, instead of saying "You ordered a hamburger", it'd be better to ask, "how many hamburger do you want?" or something similar.
Finally after exiting the loop, you can calculate the price and print the order summary.
You can declare 3 variables representing no of each items
I would work with a structure holding 2 arrays:
- 1 for items quantities.
- 1 for items prices.
Array indexs will represent a particular item, and an helper function can be in charge of translating user input to array index.

Also, by respect to SRP (Single Responsibility Principle, very important), move the code diplaying choice and handling user input to separate functions, and write functions that do 1 thing, and do it well. It will be easyer for you to re-read later, understand the logic, and track down mistakes (bugs).

With all this taken in consideration, the code can look Something like the following:
#include <stdio.h>

struct order
{
    unsigned quantities[4];
    unsigned prices[4];
};

void setOrderEmpty(order* in);
void displayChoices();
int handleUserInput(unsigned choice);
void displayOrder(order* in);
float computePrice(order* in);
float computeHST(float price);



int main()
{
    order order;
    setOrderEmpty(&order);
    int userChoice;
    do {
        displayChoices();
        printf("Enter your choice: ");

        unsigned choice;
        scanf("%ud", &choice);

        userChoice = handleUserInput(choice);
        if(userChoice >= 0)
            order.quantities[userChoice]++;
    } while (userChoice != -1);
    displayOrder(&order);
}

void setOrderEmpty(order* in)
{
    for(unsigned i=0; i<4; i++)
        in->quantities[i] = 0;
    in->prices[0] = 5;
    in->prices[1] = 4;
    in->prices[2] = 3;
    in->prices[3] = 2;
}

void displayChoices()
{
    printf("What do you want to eat today?\n");
    printf("1. Hamburger\n");
    printf("2. Hotdog\n");
    printf("3. Fries\n");
    printf("4. Exit\n");
}

int handleUserInput(unsigned choice)
{
    switch(choice) {
    case 1:
        printf("You ordered a hamburger\n");
        return 0;
        break;
    case 2:
        printf("You ordered a hotdog\n");
        return 1;
        break;
    case 3:
        printf("You ordered fries\n");
        return 2;
        break;
    case 4:
        printf("Order finished, thank you!\n");
        return -1;
        break;
    default:
        printf("Wrong choice! try again:\n");
        return -2;
        break;
    }
}

void displayOrder(order* in)
{
    printf("\nYou ordered %d hamburger(s), %d hotdog(s), %d fries, %d drink(s).", in->quantities[0], in->quantities[1], in->quantities[2], in->quantities[3]);
    unsigned price = computePrice(in);
    printf("\nPrice: $%d", price);
    float HST = computeHST(price);
    printf("\nHST: $%0.2f", HST);
    printf("\nTotal: $%0.2f", HST + price);
}

float computePrice(order* in)
{
    unsigned price = 0;
    for(unsigned i=0; i<4; i++)
        price = price + in->quantities[i] * in->prices[i];
    return price;
}

float computeHST(float price)
{
    return price * 0.216;
}

Open in new window

Note: Since I have no clue how HST is computed in your country, you'll need to adjust the formula to fit your needs.
No need of break; after return statement. It will be unreachable code
>> the code can look Something like the following:
We agree.


@Kinjal shah
$ /bin/cat Sample_code.c
/*
	Removed blank lines
	Handle Null pointer exception
	Align Open paranthesis and Close paranthesis
	Handle ( value operator variable ) instead of ( variable operator value )
	Included stdlib.h to use _exit function
	Write related comments
*/
#define CURRENCY_NAME "$"
#include <sys/unistd.h>
#include <sys/time.h>
#include <stdio.h>
struct order
{
	unsigned quantities[5];
	unsigned prices[5];
};
void setOrderEmpty( struct order* in);
void displayChoices();
int handleUserInput( unsigned choice);
void displayOrder( struct order* in);
float computePrice( struct order* in);
float computeHST( float price);
int main(int argc, const char** argv)
{
	time_t my_time = 0;
	struct tm * timeinfo = NULL;
	time (&my_time);
	timeinfo = localtime (&my_time);
	if ( 1 == argc)
	{
		printf( "Usage:\n");
		printf( "%s Sir\n", argv[0]);
		printf( "or\n");
		printf( "%s Madam\n", argv[0]);
		_exit (1);
	}
	if ( NULL == timeinfo)
	{
		printf( "main timeinfo being NULL value\n");
		_exit (1);
	}
	if ( 12 > timeinfo->tm_hour )
	{
		printf( "Good Morning %s\n", argv[1]);
	}
	else if ( 16 > timeinfo->tm_hour )
	{
		printf( "Good afternoon %s\n", argv[1]);
	}
	else
	{
		printf( "Good evening %s\n", argv[1]);
	}
	if ( 1 == (timeinfo->tm_mon+1) )
	{
		printf( "Wish you happy new year.\n");
	}
	{
		struct order CurrentOrder = {};
		setOrderEmpty(&CurrentOrder);
		int userChoice = 0;
		do {
			displayChoices();
			printf("Enter your choice: ");
			unsigned choice;
			scanf("%ud", &choice);
			userChoice = handleUserInput(choice);
			if( 0 <= userChoice )
			{
				CurrentOrder.quantities[userChoice]++;
			}
		} while ( -1 != userChoice );
		displayOrder(&CurrentOrder);
	}
}
void setOrderEmpty(struct order* in)
{
	if ( NULL == in )
	{
		printf( "setOrderEmpty in being NULL value\n");
		_exit (1);
	}
	for( unsigned OrderIndx=0; OrderIndx<5; OrderIndx++)
	{
		in->quantities[OrderIndx] = 0;
	}
	in->prices[0] = 5;
	in->prices[1] = 4;
	in->prices[2] = 3;
	in->prices[3] = 2;
	in->prices[4] = 1;
}
void displayChoices()
{
	static short FirstOrder = 'n';
	if ( 'n' == FirstOrder )
	{
		printf("May I take your order, please:?\n");
	}
	else
	{
		printf("your next order, please:?\n");
	}
	printf("1. Hamburger\n");
	printf("2. Hotdog\n");
	printf("3. Fries\n");
	printf("4. drink\n");
	printf("5. Exit\n");
}
int handleUserInput(unsigned choice)
{
	static int TotalOrders = 0;
	TotalOrders = TotalOrders + 1;
	switch(choice) {
	case 1:
		printf("You ordered a hamburger\n");
	case 2:
		printf("You ordered a hotdog\n");
		break;
	case 3:
		printf("You ordered fries\n");
		break;
	case 4:
		printf("You ordered drink(s)\n");
		break;
	case 5:
		if ( 1 == TotalOrders )
		{
			printf("Take your time. Please look into menu for available items.\n");
		}
		else
		{
			printf("Thank you! for your orders.\n");
		}
		return -1;
	default:
		printf("Wrong choice! try again:\n");
		return -2;
	}
	return choice-1;
}
void displayOrder(struct order* in)
{
	unsigned price = computePrice(in);
	if ( NULL == in )
	{
		printf( "displayOrder in being NULL value\n");
		_exit (1);
	}
	if ( ( 0 == in->quantities[0] ) && ( 0 == in->quantities[1] ) && ( 0 == in->quantities[2] ) && ( 0 == in->quantities[3] ) )
	{
		return;
	}
	printf("\nYour order list:\n");
	printf( "hamburger(s) : %d\n", in->quantities[0]);
	printf( "hotdog(s)    : %d\n", in->quantities[1]);
	printf( "fries        : %d\n", in->quantities[2]);
	printf( "drink(s)     : %d\n", in->quantities[3]);
	printf("Price: "CURRENCY_NAME" %d\n", price);
	float HST = computeHST(price);
	printf("HST  : "CURRENCY_NAME" %3.3f\n", HST);
	printf("Total: "CURRENCY_NAME" %3.3f\n", HST + price);
}
float computePrice(struct order* in)
{
	unsigned price = 0;
	if ( NULL == in )
	{
		printf( "computePrice in being NULL value\n");
		_exit (1);
	}
	for(unsigned OrderIndx=0; OrderIndx<5; OrderIndx++)
	{
		price = price + in->quantities[OrderIndx] * in->prices[OrderIndx];
	}
	return price;
}
float computeHST(float price)
{
	return price * 0.216;
}
$ /usr/bin/gcc -Wall  Sample_code.c -o ./Sample_code

Open in new window

Test results:
$ ./Sample_code
Usage:
./Sample_code Sir
or
./Sample_code Madam
$
$
$
$
$
$ ./Sample_code Madam
Good evening Madam
May I take your order, please:?
1. Hamburger
2. Hotdog
3. Fries
4. drink
5. Exit
Enter your choice: 1
You ordered a hamburger
You ordered a hotdog
May I take your order, please:?
1. Hamburger
2. Hotdog
3. Fries
4. drink
5. Exit
Enter your choice: 5
Thank you! for your orders.

Your order list:
hamburger(s) : 1
hotdog(s)    : 0
fries        : 0
drink(s)     : 0
Price: $ 5
HST  : $ 1.080
Total: $ 6.080
$
$
$
$
$ ./Sample_code Sir
Good evening Sir
May I take your order, please:?
1. Hamburger
2. Hotdog
3. Fries
4. drink
5. Exit
Enter your choice: 5
Take your time. Please look into menu for available items.
$
$
$
$
$ ./Sample_code Sir
Good evening Sir
May I take your order, please:?
1. Hamburger
2. Hotdog
3. Fries
4. drink
5. Exit
Enter your choice: 1
You ordered a hamburger
You ordered a hotdog
May I take your order, please:?
1. Hamburger
2. Hotdog
3. Fries
4. drink
5. Exit
Enter your choice: 2
You ordered a hotdog
May I take your order, please:?
1. Hamburger
2. Hotdog
3. Fries
4. drink
5. Exit
Enter your choice: 3
You ordered fries
May I take your order, please:?
1. Hamburger
2. Hotdog
3. Fries
4. drink
5. Exit
Enter your choice: 4
You ordered drink(s)
May I take your order, please:?
1. Hamburger
2. Hotdog
3. Fries
4. drink
5. Exit
Enter your choice: 5
Thank you! for your orders.

Your order list:
hamburger(s) : 1
hotdog(s)    : 1
fries        : 1
drink(s)     : 1
Price: $ 14
HST  : $ 3.024
Total: $ 17.024

Open in new window

if ( NULL == in )
	{
		printf( "computePrice in being NULL value\n");
		_exit (1);
	}

Open in new window

Better handle this with an assertion IMO.
@Kinjal shah
I agree assertion comment
but it is based on the type of testing.
Generally assert mode not provided during release mode.
Following code being sample:
$ ./TestMemoryAllocation.sh
--------------------------------------------------------
TEST 1. Assert_sample.c existence PASS
/usr/bin/gcc -Wall Assert_sample.c -o ./Assert_sample -DSAMPLE_TEST
--------------------------------------------------------
TEST 2. Compilation ASSERT_TEST Assert_sample.c PASS
./Assert_sample 2147483647
--------------------------------------------------------
TEST 3. ./Assert_sample 2147483647 PASS
--------------------------------------------------------
./Assert_sample 2147483648
SAMPLE_TEST assert
Provide valid parameter to allocate memory
--------------------------------------------------------
TEST 4. ./Assert_sample 2147483648 FAIL
--------------------------------------------------------
/usr/bin/gcc -Wall Assert_sample.c -o ./Assert_sample
--------------------------------------------------------
TEST 5. Compilation RELEASE_MODE Assert_sample.c PASS
./Assert_sample 2147483647
--------------------------------------------------------
TEST 6. ./Assert_sample 2147483647 PASS
--------------------------------------------------------
./Assert_sample 2147483648
Provide valid parameter to allocate memory
--------------------------------------------------------
TEST 7. ./Assert_sample 2147483648 FAIL
--------------------------------------------------------

Open in new window


$ /bin/cat  TestMemoryAllocation.sh
#!/bin/bash
#Sample test script
TEST_COUNT=0
if [ -f Assert_sample.c ]
then
        TEST_COUNT=$(/usr/bin/expr $TEST_COUNT + 1)
        echo "--------------------------------------------------------"
        echo "TEST $TEST_COUNT. Assert_sample.c existence PASS"
        for test_mode in ASSERT_TEST RELEASE_MODE
        do
                if [ "$test_mode" = "ASSERT_TEST" ]
                then
                        echo /usr/bin/gcc -Wall Assert_sample.c -o ./Assert_sample -DSAMPLE_TEST
                        /usr/bin/gcc -Wall Assert_sample.c -o ./Assert_sample -DSAMPLE_TEST
                else
                        echo /usr/bin/gcc -Wall Assert_sample.c -o ./Assert_sample
                        /usr/bin/gcc -Wall Assert_sample.c -o ./Assert_sample
                fi
                if [ $? -eq 0 ]
                then
                        TEST_COUNT=$(/usr/bin/expr $TEST_COUNT + 1)
                        echo "--------------------------------------------------------"
                        echo "TEST $TEST_COUNT. Compilation $test_mode Assert_sample.c PASS"
                        MAXIMUM_INTEGER=$(/bin/grep "#define INT_MAX" /usr/include/limits.h |\
                        /usr/bin/awk '{ print $NF}')
                        MAXIMUM_INTEGER=$(/bin/grep "#define $MAXIMUM_INTEGER" /usr/include/limits.h |\
                        /usr/bin/awk '{ print $NF}')
                        CURRENT_NUM=$MAXIMUM_INTEGER
                        while [ 1 ]
                        do
                                echo ./Assert_sample $CURRENT_NUM
                                ./Assert_sample $CURRENT_NUM
                                if [ $? -ne 0 ]
                                then
                                        TEST_COUNT=$(/usr/bin/expr $TEST_COUNT + 1)
                                        echo "--------------------------------------------------------"
                                        echo "TEST $TEST_COUNT. ./Assert_sample $CURRENT_NUM FAIL"
                                        echo "--------------------------------------------------------"
                                        break
                                fi
                                TEST_COUNT=$(/usr/bin/expr $TEST_COUNT + 1)
                                echo "--------------------------------------------------------"
                                echo "TEST $TEST_COUNT. ./Assert_sample $CURRENT_NUM PASS"
                                CURRENT_NUM=$(/usr/bin/expr $CURRENT_NUM + 1)
                                echo "--------------------------------------------------------"
                        done
                else
                        TEST_COUNT=$(/usr/bin/expr $TEST_COUNT + 1)
                        echo "--------------------------------------------------------"
                        echo "TEST $TEST_COUNT. Assert_sample.c Compilation $test_mode FAIL"
                        echo "--------------------------------------------------------"
                fi
        done
else
        TEST_COUNT=$(/usr/bin/expr $TEST_COUNT + 1)
        echo "--------------------------------------------------------"
        echo "TEST $TEST_COUNT. Assert_sample.c existence FAIL"
        echo "/bin/ls -l Assert_sample.c"
        /bin/ls -l "Assert_sample.c"
        echo "--------------------------------------------------------"
fi

Open in new window



$ /bin/cat  Assert_sample.c
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
// Sample code
// No optimization... related to coding
// Use valid parameter name instead of argc and argv
int main( int argc, const char** argv)
{
        char *InvalidPtr = NULL;
        if ( 1 == argc )
        {
                printf( "Usage:\n%s integer\nExample:\n%s 123456\n", argv[0], argv[0]);
                return 1;
        }
        // Not handled this using other functions.
        // This is sample.
        {
                unsigned int MemoryNumLen = strlen( argv[1]) - 1;
                while ( 0 < MemoryNumLen )
                {
                        switch( argv[1][MemoryNumLen] )
                        {
                                case '0':
                                case '1':
                                case '2':
                                case '3':
                                case '4':
                                case '5':
                                case '6':
                                case '7':
                                case '8':
                                case '9':
                                case '\n':
                                break;
                                default:
                                printf( "Provide valid parameter.\n");
                                printf( "Usage:\n");
                                printf( "%s integer\n", argv[0]);
                                printf( "Example:\n");
                                printf( "%s 123456\n", argv[0]);
                                return 2;
                        }
                        MemoryNumLen = MemoryNumLen - 1;
                }
        }
        InvalidPtr=malloc( atoi(argv[1]));
        if ( NULL == InvalidPtr )
        {
        #ifdef SAMPLE_TEST
                printf( "SAMPLE_TEST assert\n");
        #endif
                printf( "Provide valid parameter to allocate memory\n");
                return 3;
        }
        return 0;
}

Open in new window

This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.