Saturday, September 1, 2018

Queue : Array Implementation in C

#include <stdio.h>
#define QUEUE_LENGTH 50
struct queue
{
    int element[QUEUE_LENGTH];
    int front,rear,choice,x,y;
};
void traverse(struct queue q)
 {  printf("The elements of the queue are\n");
     for(int i=0;i<=q.rear;i++)
     {
         printf("%d\n",q.element[i]);
     }
 }
void add(struct queue *p,int y)
{
    if((*p).rear<QUEUE_LENGTH)
    {   (*p).rear +=1;
        (*p).element[(*p).rear]=y;
        printf("rear =  %d\n",(*p).rear);
        printf("type -1 to exit\n");
        scanf("%d",&y);
        if(y==(-1))
        {
            return;
        }
        add(p,y);
    }
    else
    {
        printf("Queue overflow\n");
    }
}
void delete(struct queue *p)
{
    int x=0,y=0;
    if((*p).front>(*p).rear)
    {
        printf("Queue empty\n");
    }
    else
    {
        x=(*p).element[(*p).front];
        (*p).element[(*p).front]=0;
        (*p).front=(*p).front+ 1;
    }
    printf("type 1 to delete or 2 to exit\n");
        scanf("%d",&y);
        if(y==(2))
        {
            return ;
        }
        if(y==(1))
        {
            traverse(*p);
            printf("%d is deleted\n",(*p).element[(*p).front]-1);
            delete(p);

        }
}
int main()
{   int choice=0,x=0;
    struct queue q;
    q.rear= -1,q.front=0;
        printf("\nEnter element to be added:\n");
        scanf("%d",&x);
        add(&q,x);
        traverse(q);
        delete(&q);
        printf("Deletion completed \n");
    return 0;
}

Output:

  1. $gcc -o main *.c
  2. $main
  3.  
  4. Enter element to be added:
  5. 1
  6. rear = 0
  7. type -1 to exit
  8. 2
  9. rear = 1
  10. type -1 to exit
  11. 3
  12. rear = 2
  13. type -1 to exit
  14. 4
  15. rear = 3
  16. type -1 to exit
  17. 5
  18. rear = 4
  19. type -1 to exit
  20. 6
  21. rear = 5
  22. type -1 to exit
  23. 7
  24. rear = 6
  25. type -1 to exit
  26. -1
  27. The elements of the queue are
  28. 1
  29. 2
  30. 3
  31. 4
  32. 5
  33. 6
  34. 7
  35. type 1 to delete or 2 to exit
  36. The elements of the queue are
  37. 0
  38. 2
  39. 3
  40. 4
  41. 5
  42. 6
  43. 7
  44. 1 is deleted
  45. type 1 to delete or 2 to exit
  46. The elements of the queue are
  47. 0
  48. 0
  49. 3
  50. 4
  51. 5
  52. 6
  53. 7
  54. 2 is deleted
  55. type 1 to delete or 2 to exit
  56. The elements of the queue are
  57. 0
  58. 0
  59. 0
  60. 4
  61. 5
  62. 6
  63. 7
  64. 3 is deleted
  65. type 1 to delete or 2 to exit
  66. Deletion completed
 
 

No comments:

Post a Comment

How can I run a C++ program directly from Windows?

How-can-I-run-a-C-program-directly-from-Windows