Question: How can I modify my code(see below) to meet the following requirements?: Your task is to change your strategy for removing items to a more

How can I modify my code(see below) to meet the following requirements?:

Your task is to change your strategy for removing items to a more efficient one. Instead of shifting each element one step to the left when an element is removed, you should now instead swap places of the item you want to remove with the last element of the array, so that the element you want to remove ends up in the last position. After that you can simply reduce the length by 1 so that the last element disappears. The drawback with this method is that it changes the order of items, but instead it is more efficient. example run (user input in bold, comments in italics): Shopping List: 1 banana 2 pcs 2 milk 1 litre 3 soda 1.5 litre 4 peanuts 100 g 5 chips 250 g 1. Add an item 2. Display the shopping list 3. Remove an item 4. Change an item 5. Save list 6. Load list 7. Exit Enter option: 3 Which item would you like to remove: 2 removes milk. Milk and chips will swap places 1. Add an item 2. Display the shopping list ... Enter option: 2 Shopping List: 1 banana 2 pcs 2 chips 250 g chips is now where milk used to be 3 soda 1.5 litre 4 peanuts 100 g

Hint: Swapping the values of two variables requires an extra variable to temporarily store the value of one of them. For example, if we want to swap the values of two integer variables x and y, we could write: int temp; temp=x; x=y; y=temp;

My code:

#define _CRT_SECURE_NO_WARNINGS #include"ShoppingList.h" #include #include // For malloc() and free() #include #include

void removeItem(struct ShoppingList* list) { if (list->length == 0) { return; } printf("Your list contains %d items ", list->length);

printList(list);

int index;

printf("Which item do you want to remove? "); scanf_s("%d", &index);

while (index < 1 || index > list->length) { printf("The list contains only %d items! ", list->length); printf("Which item do you want to remove? "); scanf_s("%d", &index); }

index--; // Since the list is numbered from 1, but the array is numbered from 0

printf("The item %s %.1f %s was removed from the list. ", list->itemList[index].productName, list->itemList[index].amount, list->itemList[index].unit);

// Shift all items one step to the left for (int i = index; i < list->length - 1; i++) { list->itemList[i] = list->itemList[i + 1]; }

list->length--; //listan blir "mindre" nr en item tas bort }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!