C++ program to implement circular queue using array

Wednesday, February 2nd, 2011
#include <iostream.h>
class cqueue
{
	private :
		int *arr ;
		int front, rear ;
		int MAX;
	public :
		cqueue( int maxsize = 10 ) ;
		void addq ( int item ) ;
		int delq( ) ;
		void display( ) ;
} ;
cqueue :: cqueue( int maxsize )
{
	MAX = maxsize ;
	arr = new int [ MAX ];
	front = rear = -1 ;
	for ( int i = 0 ; i < MAX ; i++ )
		arr[i] = 0 ;
}
void cqueue :: addq ( int item )
{
	if ( ( rear + 1 ) % MAX == front )
	{
		cout << "\nQueue is full" ;
		return ;
	}
	rear = ( rear + 1 ) % MAX;
	arr[rear] = item ;
	if ( front == -1 )
		front = 0 ;
}
int cqueue :: delq( )
{
	int data ;
	if ( front == -1 )
	{
		cout << "\nQueue is empty" ;
		return NULL ;
	}
 
	data = arr[front] ;
	arr[front] = 0 ;
	if ( front == rear )
	{
		front = -1 ;
		rear = -1 ;
	}
	else
		front = ( front + 1 ) % MAX;
	return data ;
}
void cqueue :: display( )
{
	cout << endl ;
	for ( int i = 0 ; i < MAX ; i++ )
		cout << arr[i] << "  " ;
	cout << endl ;
}
void main( )
{
	cqueue a ( 10 ) ;
	a.addq ( 14 ) ;
	a.addq ( 22 ) ;
	a.addq ( 13 ) ;
	a.addq ( -6 ) ;
	a.addq ( 25 ) ;
	cout << "\nElements in the circular queue: " ;
	a.display( ) ;
	int i = a.delq( ) ;
	cout << "Item deleted: " << i ;
	i = a.delq( ) ;
	cout << "\nItem deleted: " << i ;
	cout << "\nElements in the circular queue after deletion: " ;
	a.display( ) ;
	a.addq ( 21 ) ;
	a.addq ( 17 ) ;
	a.addq ( 18 ) ;
	a.addq ( 9 ) ;
	a.addq ( 20 ) ;
	cout << "Elements in the circular queue after addition: " ;
	a.display( ) ;
	a.addq ( 32 ) ;
	cout << "Elements in the circular queue after addition: " ;
	a.display( ) ;
}
Avatar of Ranjith

Author Name :
Ranjith

Total : 5 Comments


5 Responses to “C++ program to implement circular queue using array”

  1. dummy says:

    there is no ‘queue is full’ concept in circular buffer. you need to modify ur code to rollover the rear piinter.

  2. nehemiah says:

    @ Dummy….Not necessary pal…There are many ways to look at it..
    If you ask me I will write 3 methods or one method with three modes

    - Enqueue Soft – Just tries to add element, fails if the queue is full
    - Enqueue Hard – Somehow adds the element by allocating extra memory
    - Enqueue Forced – This is what you are talking about, It simply adds the element by dropping the first element(dequeued)

  3. nehemiah says:

    @ Author…Why don’t you templatize this program so that it can take any type of elements?

  4. unknown says:

    this code is wrong it doesn’t move the item inside it

  5. dasa says:

    bkwass mariiii hoi haiiiiiiiiiiiiiiiiii

Leave a Reply

Question and Answer
C/C++ Unix & Linux Wordpress
Source codes
C C++ Java

Free email signup

Email: