Circular Queue Using Arrays

/*******************************************************************************/
#include <stdio.h>
#include<stdlib.h>
#include <stdbool.h>
#define MAX 10
// initilazing queue
int cqueue[MAX];
int rear = - 1;
int front = -1;
// Function to check if the cqueue is empty
bool isEmpty() {
    return front==-1 ;
}

// Function to check if the cqueue is full
bool isFull() {
    return (rear+1)%MAX == front;
}

void insert() // enqueue
{
int item;
if (isFull())
  printf("Queue Overflow \n");
else
 {
 printf("\nInset the element in queue : ");
 scanf("%d", &item);
    if(isEmpty())
       front=rear=0;
    else
      rear = (rear + 1)%MAX;
 cqueue[rear] = item;
 }
} /*End of insert()*/
void delete() //dequeue
{
     if(isEmpty())
     {
       printf("\nQueue Underflow \n");
       return ;
     }
     printf("\nElement deleted from queue is : %d\n", cqueue[front]);
    
if ( rear == front )
    {
    front=rear=-1;//make it empty
    }
    else
    {
    front = (front + 1) %MAX;
    }
} /*End of delete() */
void display()// print queue
{
int i;
    if (isEmpty() )
        printf("\nQueue is empty \n");
     else
    {  printf("\nQueue is : ");
        if(front==rear)
            printf("%d\n", cqueue[front]);
        else
        {
        for (i = front; i != rear; i=(i+1)%MAX)
            printf("%d ", cqueue[i]);
        
        printf("%d ", cqueue[i]); //print the element at rear
        printf("\n");
        }
    }
}
// Function to peek at the front item
int peek() {
    if (isEmpty()) {
        printf("Queue is empty. Nothing to peek.\n");
        return -1; // Error value
    } else {
        return cqueue[front];
    }
}
// Function to get the size of the queue
int size() {
    if (isEmpty()) {
        return 0;
    } else {
        if (rear >= front ) return rear - front + 1;
        else return MAX-front+rear-0+1;
    }
}
int main()
{
int choice;
while (1)
{
printf("\n1.Insert element to queue \n");
printf("2.Delete element from queue \n");
printf("3.Display all elements of queue \n");
printf("4.Peek \n");
printf("5.Size of the queue\n");
printf("6.Quit \n");
printf("\nEnter your choice : ");
scanf("%d", &choice);
switch (choice)
{
case 1:
    insert();
    break;
case 2:
    delete();
    break;
case 3:
    display();
    break;
case 4:
    int x=peek();
    if(x!=-1) printf("\nfront element is=%d\n",x);
    break;
case 5:
    printf("\nsize of the queue is =%d\n",size());
    break;
case 6:
    exit(1);

default:

printf("\nWrong choice \n");

} /*End of switch*/

} /*End of while*/
return 0;
} /*End of main()*/

Comments

Popular posts from this blog

Data Structure Lab CSL 201 Manual KTU - Dr Binu V P-9847390760

Singly Linked List Implementation

Binary search Tree Implementation and Traversal