Facebook
From mythreyan, 2 Months ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 131
  1. PRODUCER CONSUMER
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4.  
  5. #define BUFFER_SIZE 5
  6. #define NUM_ITEMS 10
  7.  
  8. int buffer[BUFFER_SIZE];
  9. int count = 0;
  10. int in = 0;
  11. int out = 0;
  12.  
  13. void produce() {
  14.     if (count < BUFFER_SIZE) {
  15.         int item = rand() % 100;
  16.         buffer[in] = item;
  17.         in = (in + 1) % BUFFER_SIZE;
  18.         count++;
  19.         printf("Produced: %d\n", item);
  20.     } else {
  21.         printf("Buffer is full! Cannot produce.\n");
  22.     }
  23. }
  24.  
  25. void consume() {
  26.     if (count > 0) {
  27.         int item = buffer[out];
  28.         out = (out + 1) % BUFFER_SIZE;
  29.         count--;
  30.         printf("Consumed: %d\n", item);
  31.     } else {
  32.         printf("Buffer is empty! Cannot consume.\n");
  33.     }
  34. }
  35.  
  36. int main() {
  37.     int producedCount = 0;
  38.     int consumedCount = 0;
  39.     int choice;
  40.  
  41.     while (producedCount < NUM_ITEMS || consumedCount < NUM_ITEMS) {
  42.         printf("\nSelect an operation:\n1. Produce\n2. Consume\nChoice: ");
  43.         scanf("%d", &choice;);
  44.  
  45.         switch (choice) {
  46.             case 1:
  47.                 if (producedCount < NUM_ITEMS) {
  48.                     produce();
  49.                     producedCount++;
  50.                 } else {
  51.                     printf("All items produced! Cannot produce more.\n");
  52.                 }
  53.                 break;
  54.  
  55.             case 2:
  56.                 if (consumedCount < NUM_ITEMS) {
  57.                     consume();
  58.                     consumedCount++;
  59.                 } else {
  60.                     printf("All items consumed! Cannot consume more.\n");
  61.                 }
  62.                 break;
  63.  
  64.             default:
  65.                 printf("Invalid choice! Please select 1 to produce or 2 to consume.\n");
  66.         }
  67.     }
  68.  
  69.     printf("Production and consumption completed.\n");
  70.  
  71.     return 0;
  72. }
  73.