Menu Close

Queue using arrays in c

Static Queue:

  • We can use simple array with fixed size.
  • All operations need to perform using 2 variables Front and Rear.
  • Front is always pointing to Front location that is 0 index.

Declaration as follows:

	#define SIZE 5
	int queue[SIZE];
	int front=0 , rear=0 ;

Operations:

  1. Insert()
  2. Delete()
  3. Traverse()
  4. isEmpty()
  5. isFull()

Insertion:

  • Checking Queue is Full or not
  • If Queue is Full -> Display “Queue is Overflow”.
  • If not, we insert the element from rear (using rear variable)

Why rear starts with 0 index?

  • ‘front’ location is fixed in Queue.
  • Hence ‘front’ value cannot modify while application is running
  • ‘front’ index is 0 always.
  • Along with front value, we initialize ‘rear’ value as 0

Deletion:

  • We perform deletion from “Front”.
  • Once we delete front element, we should not move “front” as “Front++”.
  • “front” is fixed in “linear queue”
  • All elements need to shift by one location towards front after deletion

Traverse():

  • If Queue is Empty – “Queue is underflow”
  • Else display elements from Front to Rear-1

Queue Program using Arrays:

  • Array is a linear representation of elements
  • We can implement queue operations simply using array concept
  • Array can be represented as Queue with logic implementation
  • We perform all operations on Queue using functions
#include<stdio.h>
#define SIZE 5
int queue[], front=0 , rear=0 ;

void insert(int ele);
int delete(void);
int isFull(void);
int isEmpty(void);
void display(void);

int main()
{
	int ch, ele ;
	while(1)
	{
		printf("1. Insert \n");
		printf("2. Delete \n");
		printf("3. Display \n");
		printf("4. Quit \n");

		printf("Enter your choice : ");
		scanf("%d", &ch);

		switch(ch)
		{
			case 1	:	printf("Enter element : ");
					scanf("%d", &ele);
					insert(ele);
					break ;
			
			case 2	:	ele = delete();
					if(ele)
					{
						printf("Deleted : %d \n",ele);
					}
					else
					{
						printf("Queue is empty \n");
					}
					break ;
			
			case 3	:	display();
					break;
			
			case 4	:	exit(1);
			default	:	printf("Invalid choice\n");
		}
	}
	return 0 ;
}
void insert(int ele)
{
	if(isFull())
	{
		printf("Queue is Full...\n");
	}
	else
	{
		queue[rear] = ele ;
		rear++;
		printf("Inserted...\n");
	}
}
int delete(void)
{
	if(isEmpty())
	{
		return 0 ;
	}
	else
	{
		int ele,i ;
		ele = queue[front];
		for(i=front ; i<rear-1 ; i++)
		{
			queue[i] = queue[i+1];
		}
		rear--;
		return ele ;
	}
}
int isFull(void)
{
	if(rear == SIZE)
		return 1 ;
	else
		return 0 ;
}
int isEmpty(void)
{
	if(front==rear)
		return 1 ;
	else
		return 0 ;
}
void display(void)
{
	int i;
	if(isEmpty())
	{
		printf("Queue is Empty\n");
	}
	else
	{
		printf("Queue elements are");
		for(i=front ; i<rear ; i++)
		{
			printf("%d \n", queue[i]);
		}
	}
}