Question

You are off to shopping and need a program that allows you to enter the names...

You are off to shopping and need a program that allows you to enter the names of items, their price and quantities. Here is what a sample run should look like (with the keyboard input shown in italics) ...

    Enter item information ("exit" to exit)
    item 1: chips
    price: 3.5
    quantity: 2
    Enter item information ("exit" to exit)
    item 2: red wine
    price : 15.0
    quantity : 1
    Enter item information ("exit" to exit)
    item 3 : steaks
    price : 15.0
    quantity : 2
        
    Your list:
    steaks               2    $30
    red wine             1    $15
    chips                2    $7
    -----------------------------
    Total                     $52

You must ...

  • Implement the program in C. (3.0%)
    • An array of structures must be used, so that each new item can be recorded in an element of the array.
    • It's not known in advance how many new items will be added to the list, so the program must malloc for an initial array of size 1, and use the doubling realloc technique (as discussed in class) to get more memory as required. You must always check the return value from malloc, as done in the Malloc wrapper function (or just use Malloc :-).
    • After you are done building the shopping list you must sort the array of structures according to the total price of each item.
    • Before the program completes it must explicitly free the malloced memory.
0 0
Add a comment Improve this question Transcribed image text
Answer #1

//--------- ShoppingCart.c --------------

#include<stdio.h>
#include<malloc.h>
#include<string.h>
typedef struct Item
{
   char name[100];
   float price;
   int quantity;
}Item;
Item* reAllocate(Item items[],int *size)
{
   int newSize = *size * 2;
   Item *newItems = (Item *) malloc(sizeof(Item) * newSize);
   int i = 0;
   for(i = 0;i<*size;i++)
   {
       strcpy(newItems[i].name,items[i].name);
       newItems[i].price = items[i].price;
       newItems[i].quantity = items[i].quantity;
   }
   *size = newSize;
   return newItems;
  
}
void copyItem(Item *target, Item src)
{
   strcpy(target->name , src.name);
   target->price = src.price;
   target->quantity = src.quantity;
}
void swapItem(Item *one,Item *two)
{
   Item temp;
   copyItem(&temp,*one);
   copyItem(one,*two);
   copyItem(two,temp);
  
}
void sortItems(Item items[], int size)
{
   int i,j;
   float totalOne,totalTwo;
   for(i = 0;i<size;i++)
   {
       for(j = 0;j<size-i-1;j++)
       {
           totalOne = items[j].price * items[j].quantity;
           totalTwo = items[j+1].price * items[j+1].quantity;
           if(totalOne <totalTwo)
           {
               swapItem(items+j,items+j+1);
           }
       }
   }
}
void printItems(Item items[], int size)
{
   int i;
   printf("\nYour List\n");
   float totalPrice = 0;
   float itemTotal = 0;
   for(i = 0;i<size;i++)
   {
       itemTotal = items[i].price*items[i].quantity;
       printf("\n%-20s %-10d %-10.2f\n",items[i].name,items[i].quantity,itemTotal);
       totalPrice += itemTotal;
   }
   printf("\n----------------------------------------\n");
   printf("Total %30.2f\n",totalPrice);
}
int main()
{
   int size = 1;
   Item* items = (Item *) malloc(sizeof(Item) * size);
   char name[100];
   float price;
   int quantity;
   char ch;
   int itemPos = 0;
   do
   {
       printf("\nEnter item Informaation (\"exit\" to exit)\n");
       printf("Item %d: ",itemPos+1);
       gets(name);
       if(strcmp(name,"exit") == 0)
       {
           break;
       }
       printf("price: ");
       scanf("%f",&price);
       if(price <0)
       {
           printf("\nError: Price cannot be negative");
           continue;
       }
       printf("quantity: ");
       scanf("%d",&quantity);
       scanf("%c",&ch);
       if(quantity <=0)
       {
           printf("\nError: Quantity cannot be negative or zero");
           continue;
       }
       strcpy(items[itemPos].name,name);
       items[itemPos].quantity = quantity;
       items[itemPos].price = price;
       itemPos++;
       if(itemPos == size)
       {
           items = reAllocate(items,&size);
       }
   }while(strcmp(name,"exit") != 0);
  
   sortItems(items,itemPos);
   printItems(items,itemPos);
   return 0;
}

//------------ OUTPUT -------------

Add a comment
Know the answer?
Add Answer to:
You are off to shopping and need a program that allows you to enter the names...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • 11.12 LAB*: Program: Online shopping cart (continued) This program extends the earlier "Online shopping cart" pr...

    11.12 LAB*: Program: Online shopping cart (continued)This program extends the earlier "Online shopping cart" program. (Consider first saving your earlier program).(1) Extend the ItemToPurchase class to contain a new attribute. (2 pts)item_description (string) - Set to "none" in default constructorImplement the following method for the ItemToPurchase class.print_item_description() - Prints item_description attribute for an ItemToPurchase object. Has an ItemToPurchase parameter.Ex. of print_item_description() output:Bottled Water: Deer Park, 12 oz.(2) Build the ShoppingCart class with the following data attributes and related methods. Note: Some can be method stubs...

  • Q1 (2 pts) Shopping list Write a program that prompts a user for items on their...

    Q1 (2 pts) Shopping list Write a program that prompts a user for items on their shopping list and keeps prompting the user until they enter "Done" (make sure your program can stop even if the user enters "Done" with different cases, like "done"), then prints out the items in the list, line by line, and prints the total number of items on the shopping list. Output (after collecting items in the while loop) should look something like this: Apple...

  • 7.11 LAB: Online shopping cart - Part 2 This program extends the earlier "Online shopping cart" program. (Consid...

    7.11 LAB: Online shopping cart - Part 2 This program extends the earlier "Online shopping cart" program. (Consider first saving your earlier program). (1) Extend the ItemToPurchase namedtuple to contain a new attribute. (2 pts) item_description (string) - Set to "none" in the construct_item() function Implement the following function with an ItemToPurchase as a parameter. print_item_description() - Prints item_name and item_description attribute for an ItemToPurchase namedtuple. Has an ItemToPurchase parameter. Ex. of print_item_description() output: Bottled Water: Deer Park, 12 oz....

  • Question: C Programming Problem: Pointer and Struct Description: The purpose of this assignment is to prov......

    Question: C Programming Problem: Pointer and Struct Description: The purpose of this assignment is to prov... C Programming Problem: Pointer and Struct Description: The purpose of this assignment is to provide practice programming using structs and pointers. Your program will accept user input and store it in a dynamic array of structs. First, you will define a structure to describe a item to be bought. Your program will prompt the user for the initial size of the array. It will...

  • 8.7 LAB*: Program: Online shopping cart (Part 2)

    8.7 LAB*: Program: Online shopping cart (Part 2)Note: Creating multiple Scanner objects for the same input stream yields unexpected behavior. Thus, good practice is to use a single Scanner object for reading input from System.in. That Scanner object can be passed as an argument to any methods that read input.This program extends the earlier "Online shopping cart" program. (Consider first saving your earlier program).(1) Extend the ItemToPurchase class per the following specifications:Private fieldsstring itemDescription - Initialized in default constructor to "none"Parameterized...

  • working on a Python program, making a shopping list giving the user several options:to view the...

    working on a Python program, making a shopping list giving the user several options:to view the list, to add an item or to delete and an option to exit the program. It's not working at all. please help. File Edit Format Run Options Window Help class shopping: det init (self, final list): self.final_list=1 det add_item(self, item): self.final list.append(item] print("The added temi " + str(item) + ".") det delete item(self, item): gelf.final list.remove(item) print (the deleted item is "+ste (item) +".")...

  • Zybooks 11.12 LAB*: Program: Online shopping cart (continued) Python 3 is the code needed and this...

    Zybooks 11.12 LAB*: Program: Online shopping cart (continued) Python 3 is the code needed and this is in Zybooks Existing Code # Type code for classes here class ItemToPurchase: def __init__(self, item_name="none", item_price=0, item_quantity=0): self.item_name = item_name self.item_price = item_price self.item_quantity = item_quantity # def __mul__(self): # print_item_cost = (self.item_quantity * self.item_price) # return '{} {} @ ${} = ${}' .format(self_item_name, self.item_quantity, self.item_price, print_item_cost) def print_item_cost(self): self.print_cost = (self.item_quantity * self.item_price) print(('{} {} @ ${} = ${}') .format(self.item_name, self.item_quantity, self.item_price,...

  • 4.18 Ch 7 Program: Online shopping cart (continued) (C++) This program extends the earlier "Online shopping...

    4.18 Ch 7 Program: Online shopping cart (continued) (C++) This program extends the earlier "Online shopping cart" program. (solution from previous lab assignment is provided in Canvas). (1) Extend the ItemToPurchase class per the following specifications: Parameterized constructor to assign item name, item description, item price, and item quantity (default values of 0). (1 pt) Public member functions SetDescription() mutator & GetDescription() accessor (2 pts) PrintItemCost() - Outputs the item name followed by the quantity, price, and subtotal PrintItemDescription() -...

  • Assignment: Write a program in C++ that allows a customer to go on-line shopping. This is...

    Assignment: Write a program in C++ that allows a customer to go on-line shopping. This is a start-up venture and the stock of our on-line company is currently limited to the following items: A gift card to Home Depot, $50.00 A bottle of cologne (The One by Dolce Gabbana), $24.00 3. Akeychainwithabathtubornament,$14.00 4. Acard,$4.00 Although all items are in stock, the customer should only be made aware of the items that he or she can afford. In addition, demand for...

  • This program extends the earlier "Online shopping cart" program. (Consider first saving your earlier program).

    Ch 7 Program: Online shopping cart (continued) (Java)This program extends the earlier "Online shopping cart" program. (Consider first saving your earlier program).(1) Extend the ItemToPurchase class per the following specifications:Private fieldsstring itemDescription - Initialized in default constructor to "none"Parameterized constructor to assign item name, item description, item price, and item quantity (default values of 0). (1 pt)Public member methodssetDescription() mutator & getDescription() accessor (2 pts)printItemCost() - Outputs the item name followed by the quantity, price, and subtotalprintItemDescription() - Outputs the...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT