Practical 4. Program based on hashing.(Icecream Shop) - SCIENCE BUZZ

Practical 4. Program based on hashing.(Icecream Shop)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TABLE_SIZE 10
typedef struct Node {
 char flavor[50];
 float sales;
 struct Node* next;
} Node;
Node* hashTable[TABLE_SIZE];
int hash(char* flavor) {
 int hashValue = 0;
 for (int i = 0; flavor[i] != '\0'; i++) {
 hashValue += flavor[i];
 }
 return hashValue % TABLE_SIZE;
}
void add_sales(char* flavor, float amount) {
 int index = hash(flavor);
 Node* current = hashTable[index];
while (current != NULL) {
 if (strcmp(current->flavor, flavor) == 0) {
 current->sales += amount;
 return;
 }
 current = current->next;
 }
 Node* newNode = (Node*)malloc(sizeof(Node));
 strcpy(newNode->flavor, flavor);
 newNode->sales = amount;
 newNode->next = hashTable[index];
 hashTable[index] = newNode;
}
// Function to display total sales for all flavors
void display_sales() {
 printf("\nIce Cream Sales Report:\n");
 for (int i = 0; i < TABLE_SIZE; i++) {
 Node* current = hashTable[i];
 while (current != NULL) {
 printf("Flavor: %s, Total Sales: $%.2f\n", current->flavor,
current->sales);
 current = current->next;
 }
}
}
void free_table() {
 for (int i = 0; i < TABLE_SIZE; i++) {
 Node* current = hashTable[i];
 while (current != NULL) {
 Node* temp = current;
 current = current->next;
 free(temp);
 }
 }
}
int main() {
 int choice;
 char flavor[50];
 float amount;
 while (1) {
 printf("\nIce Cream Shop Menu:\n");
 printf("1. Add Sales\n");
 printf("2. Display Total Sales\n");
 printf("3. Exit\n");
 printf("Enter your choice: ");
scanf("%d", &choice);
 switch (choice) {
 case 1:
 printf("Enter ice cream flavor: ");
 scanf("%s", flavor);
 printf("Enter sales amount: ");
 scanf("%f", &amount);
 add_sales(flavor, amount);
 printf("Sales of $%.2f added for %s.\n", amount, flavor);
 break;
 case 2:
 display_sales();
 break;
 case 3:
 free_table();
 printf("Exiting the program.\n");
 return 0;
 default:
 printf("Invalid choice! Please try again.\n");
 }
 }
Return 0;
}
Practical 4. Program based on hashing.(Icecream Shop) Practical 4. Program based on hashing.(Icecream Shop) Reviewed by RISHI and ARYAN on 21:24 Rating: 5

No comments:

May I help you ?

Powered by Blogger.