Implementation of Queue Using Array In C

Implementation of Queue Using Array In C

What is a Queue?

Queue is a data structure in C which follows First In First Out (FIFO) principle. Meaning the first element which is inserted in the queue will be first deleted and then the second element and so on.


Implementation of Queue Using Array In C


Operations on Queue


Deletion of element in queue is called as Dequeue

Insertion of element in queue is called as Enqueue


//Implementation of Queue Using Array

#include<stdio.h>
#include<stdlib.h>
#define size 4

int front = 0;
int rear = 0;

int queue[size];


void enqueue(int a)
{
    if(rear == size){
        printf("Queue is full");
}
    else{
        queue[rear]=a;
        rear++;
}
        
}


void dequeue()
{
    if(front==rear)
        printf("Stack is empty");
    else{
        printf("Dequed element is %d\n", queue[front]);
        front++;
   }     
}

void display(){
int i;
for(i=front;i<rear;i++){
printf("%d\n",queue[i]);
            }   
         }   

int main()
{
    enqueue(1);
    enqueue(2);
    enqueue(3);
    dequeue();
    display();
    return 0;
}

Output

Dequed element is 1
2
3


Explanation 

  • First we will allocate the size of array. After this we will declare two variables intialize to 0.
  • These two variables will traverse. We can use this traversing to add and delete element.
  • For insertion we will insert the element at the rear and increment the rear by 1.
  • For deletion we will delete the element at the front and increment the front by 1.
  • Now we will call the funtion in main.


Load comments